Beltway
Beltway

Reputation: 602

How to handle DBContext instancing in Entity Framework Core

Coming from a Java environment I'm having a few issues wrapping my head about the inheritable DBContext class. with Java EE I used to:

  1. Set up one or multiple DB Contexts (if separate clusters of entities where affected);
  2. Added the Context to respective DataAccessor classes that handled the query execution via DI;

Now with EF Core practically all samples I see create an instance of a MyDBContext by calling the default constructor:

 using (var db = new myContext()){...}

This raises a few questions for me:

Upvotes: 0

Views: 501

Answers (1)

Yehor Androsov
Yehor Androsov

Reputation: 6152

Normally you would want single instance per request scope

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        // use options as you would use them in the .OnConfiguring
        options.UseSqlServer("your connectionString");
    );
}

If you use constructor injection in services, ASP.NET service provider will resolve db context as constructor parameter. All services that have db context this way will share same instance.

public class ServiceDependentOnContext
{
    private readonly ApplicationDbContext dbContext;

    public ServiceDependentOnContext(ApplicationDbContext dbContext)
    {
        this.dbContext = dbContext;
    }
}

Make sure you configure your service for dependency injection as well

// This method gets called by the runtime. Use this method to add services to the container.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer("your connectionString")
    );

    services.AddScoped<ServiceDependentOnContext>();
}

Upvotes: 2

Related Questions