Solve DBContext using a different interface in Asp.Net Core

I have an EF context that has a 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 this causes problems when I enter an IDbContext like this

services.AddScoped(typeof(IDbContext), typeof(MyContext));

Because it duplicates my DbContext, and it should be only one per request.

How can I solve it?

+4
source share
1 answer

In your case, using the factory method should work fine.

services.AddScoped<IDbContext>(provider => provider.GetService(typeof(MyContext)));

This way you will allow a new instance MyDbContext(on the first call) or return the instance that was already instantiated during the request for final calls.

+4
source

Source: https://habr.com/ru/post/1658744/


All Articles