I have an EF Context that has it's signature
public class MyContext : DbContext, IDbContext
{
}
When I add it to services, I use it
services.AddDbContext<MyContext>(op =>
{
op.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
});
But it's causing problems when I'm injecting the IDbContext, like this
services.AddScoped(typeof(IDbContext), typeof(MyContext));
Because it's duplicating my DbContext, and It should be only one per request.
How can I resolve it?
In your case using the factory method should work fine.
services.AddScoped<IDbContext>(provider => provider.GetService(typeof(MyContext)));
This way you will resolve a new instance of MyDbContext
(on first call) or return the already instantiated instance of it during a request on conclusive calls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With