-
Notifications
You must be signed in to change notification settings - Fork 3.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Injecting DbContext, not the actual implementation #4558
Comments
Hey, Hopefully this may help you in some way. What I'd do in this scenario is:
Please let me know if you have any problems with this code, or if it isn't quite what you're looking for. Cheers :) |
Emm, you can't interface |
Sorry, that was my stupid mistake, I put DbContext in the wrong place and it should be on the Context class. I've changed it accordingly. Good luck :) |
I actually ran into #4441 problem, of contexts being scoped, which results in "object's already disposed" errors. I still baffled on why replacing AddDbContext scoped creation with your own transient |
@ajcvickers could you comment on this one. We do something with scoping on DbContext right? |
Closing this as the relevant changes in #4668 have now been merged. AddDbContext still registers the context as scoped if the context type is not yet registered, but a registration with a different lifetime can now be made either before or after with AddTransient or AddSingleton. Your context class will now need to take a |
I think I stumbled on this, I managed to make it work like this: Assume following classes public class AppDbContext : DbContext {...}
public class SpecificDbContext : AppDbContext {...} Then startup like this: var services = new ServiceCollection();
services.AddEntityFramework().AddDbContext<SpecificDbContext>(...)); The EntityFramework uses In order to use the services.AddScoped<AppDbContext, SpecificDbContext>(f =>
{
return f.GetService<SpecificDbContext >();
}); Or for DbContext injection, use this: services.AddScoped<DbContext, SpecificDbContext>(f =>
{
return f.GetService<SpecificDbContext >();
}); This way the injection works with right instance. It won't work correctly with |
Thanks @Ciantic , nice solution.
Why? Because registering AppDbContext requires the EF DbContext service? |
Is there a way to use
AddDbContext<TContext>
, to inject a particular implementation ofDbContext
without actually forcing other layers to depend on context's implementation? RegisteringDbContext
implementation usingAddDbContext<Context>
, doesn't allow usingDbContext
as aService
constructor parameter.I tried a lot of DI configurations and couldn't manage this to work.
I would want to wire it up by hand like this, but it doesn't work now.
The text was updated successfully, but these errors were encountered: