Reputation: 602
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:
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:
OnConfiguring(...)
to pass the options, but instead used AddDbContext
as a Service in Startup.cs
? Now the overloaded constructor with the options expects them to be passed on each time the constructor is called.Upvotes: 0
Views: 501
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