如何在实体框架核心中处理DBContext实例化

时间:2020-10-21 06:25:28

标签: c# entity-framework-core

来自Java环境,我遇到了一些有关可继承DBContext类的问题。使用Java EE,我曾经:

  1. 设置一个或多个数据库上下文(如果受影响的是单独的实体簇);
  2. 将上下文添加到通过DI处理查询执行的各个DataAccessor类中;

现在有了EF Core,我看到的几乎所有示例都通过调用默认构造函数来创建MyDBContext的实例:

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

这对我提出了一些问题:

  • 使用此方法,每个调用构造函数的DataAccessor类都有其自己的Context实例。只需要一个并在需要时使用DI注入它会更好吗?
  • 如果我没有重载OnConfiguring(...)来传递选项,而是在AddDbContext中将Startup.cs用作服务,该如何调用构造函数?现在,带有选项的重载构造函数希望每次调用该构造函数时都将传递它们。
  • 每个应用程序/ Db是否有多个DBContext,甚至是EF Core的一种好习惯?

1 个答案:

答案 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>();
}