[英]How to handle DBContext instancing in Entity Framework Core
来自 Java 环境,我遇到了一些关于可继承 DBContext 类的问题。 使用 Java EE 我曾经:
现在使用 EF Core,我看到的几乎所有示例都通过调用默认构造函数来创建 MyDBContext 的实例:
using (var db = new myContext()){...}
这给我提出了几个问题:
OnConfiguring(...)
来传递选项,而是在Startup.cs
使用AddDbContext
作为服务,我该如何调用构造函数? 现在带有选项的重载构造函数期望在每次调用构造函数时传递它们。通常,您需要每个请求范围的单个实例
// 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 服务提供程序会将 db 上下文解析为构造函数参数。 以这种方式具有数据库上下文的所有服务将共享相同的实例。
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>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.