Better way to get application services from within a derived DbContext instance
See original GitHub issueI am trying to get a service from within a derived DbContext
using the following code:
((IInfrastructure<IServiceProvider>)this).GetService<IMyService>();
The IMyService
was previously registered in ConfigureServices
in the Startup
class. However, the call returns null
. I am assuming this is because EF creates a service scope.
My question is how can I get a service that was registered in the Startup
class from within a derived DbContext
instance. Or, if that makes more sense, how do I register a service in EF’s service scope.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:4
- Comments:9 (5 by maintainers)
Top Results From Across the Web
Better way to get application services from within a derived ...
I am trying to get a service from within a derived DbContext using the following code: ((IInfrastructure )this).
Read more >Get service inside derived DbContext
OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext ...
Read more >Design-time DbContext Creation - EF Core
If the DbContext can't be obtained from the application service provider, the tools look for the derived DbContext type inside the project. Then ......
Read more >Managing DbContext the right way with Entity Framework 6
This precludes using lazy-loading outside of services (which can be addressed by modeling your domain using DDD or by getting services to return ......
Read more >Working with DbContext - EF6
The recommended way to work with context is to define a class that derives from DbContext and exposes DbSet properties that represent ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@ajcvickers IMHO, not being able to access the application services from EF code is really annoying, as it makes a bunch of scenarios really hard to implement. For instance, you can’t create a
IModelCustomizer
that relies on a service defined inStartup.ConfigureServices
, as EF uses its own internal service provider.@ajcvickers was there a particular reason not to make the application service provider accessible from EF’s infrastructure stuff?
@PinpointTownes This is the usual way to replace the internal service provider for ASP.NET apps:
With regards to ReplaceService, EF has no knowledge of the application service provider unless it passed to EF using UseInternalServiceProvider.