来自Java环境,我遇到了一些有关可继承DBContext类的问题。使用Java EE,我曾经:
现在有了EF Core,我看到的几乎所有示例都通过调用默认构造函数来创建MyDBContext的实例:
using (var db = new myContext()){...}
这对我提出了一些问题:
OnConfiguring(...)
来传递选项,而是在AddDbContext
中将Startup.cs
用作服务,该如何调用构造函数?现在,带有选项的重载构造函数希望每次调用该构造函数时都将传递它们。答案 0 :(得分:2)
通常,您希望每个请求范围内只有一个实例
// 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");
);
}
如果在服务中使用构造函数注入,则ASP.NET服务提供程序会将数据库上下文解析为构造函数参数。通过这种方式具有数据库上下文的所有服务将共享同一实例。
public class ServiceDependentOnContext
{
private readonly ApplicationDbContext dbContext;
public ServiceDependentOnContext(ApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}
}
确保同时配置服务以进行依赖项注入
// 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>();
}