通常,DbContext 会被添加到 Startup.ConfigureServices() 中的依赖注入容器中,如下所示:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add DbContext to the injection container
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(
this.Configuration.GetConnectionString("DefaultConnection")));
}
}
但是,IServiceCollection 不充当服务提供者,并且由于 DbContext 未在当前范围 (Startup.ConfigureServices)之前向注入容器注册,因此我们可以'这里不通过依赖注入访问上下文。
Henk Mollema 讨论了在启动期间手动解析服务 here,但提到...
手动解析服务(又名服务定位器)是generally
considered an anti-pattern ... [并且] 你应该尽可能避免它
尽可能。
Henk 还提到Startup 构造函数的依赖注入非常有限,不包括在Startup.ConfigureServices() 中配置的服务,因此通过在整个应用程序中使用的注入容器,DbContext 的使用是最简单和最合适的。
运行时的托管服务提供者可以将某些服务注入到Startup类的构造函数中,例如IConfiguration、IWebHostEnvironment(3.0之前的版本为IHostingEnvironment)、ILoggerFactory和IServiceProvider。请注意,后者是托管层构建的实例,仅包含启动应用程序的基本服务。
为了调用Database.EnsureCreated() 或Database.Migrate(),我们可以并且希望在Startup.Configure() 中自动解析 DbContext,我们配置的服务现在可以通过 DI 获得:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add DbContext to the injection container
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(
this.Configuration.GetConnectionString("DefaultConnection")));
}
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env, MyDbContext context)
{
if (env.IsDevelopment())
{
context.Database.EnsureCreated();
//context.Database.Migrate();
}
}
}
请记住 Bassam Alugili's answer 引用自 EF Core 文档,Database.EnsureCreated() 和 Database.Migrate() 不能一起使用,因为它们可以确保将现有迁移应用到数据库,该数据库是在需要时创建的。另一个只是确保数据库存在,如果不存在,则创建一个反映您的 DbContext 的数据库,包括通过上下文中的 Fluent API 完成的任何播种。