【问题标题】:Inject ApplicationDbContext into Configure method in Startup在 Startup 中将 ApplicationDbContext 注入到 Configure 方法中
【发布时间】:2023-03-18 08:30:01
【问题描述】:

我正在使用 EntityFrameworkCore 2.0.0-preview2-final,我想将 ApplicationDbContext 注入到 Startup 类的 Configure 方法中。

这是我的代码:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context)
{ 
    // rest of my code
}

但是当我运行我的应用程序时,我收到一条错误消息:

System.InvalidOperationException:无法解析范围服务 来自根提供商的“ProjectName.Models.ApplicationDbContext”。

这也是我来自 ConfigureServices 方法的代码:

services.AddDbContext<ApplicationDbContext>(options =>
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            }
            else
            {
                options.UseSqlite("Data Source=travelingowe.db");
            }
        });

你知道我该如何解决这个问题吗?

【问题讨论】:

    标签: c# entity-framework asp.net-core .net-core entity-framework-core


    【解决方案1】:

    这适用于 2.0.0 RTM。我们已经做到了,以便在调用 Configure 期间有一个范围,以便您最初编写的代码可以工作。详情请见https://github.com/aspnet/Hosting/pull/1106

    【讨论】:

      【解决方案2】:

      EF Core DbContext 注册了范围生活方式。在 ASP 原生 DI 容器范围内连接到 IServiceProvider 的实例。通常,当您使用 Controller 中的 DbContext 时没有问题,因为 ASP 为每个请求创建新范围(IServiceProvider 的新实例),然后使用它来解决此请求中的所有内容。但是,在应用程序启动期间,您没有请求范围,因此您应该自己创建范围。你可以这样做:

      var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
      using (var scope = scopeFactory.CreateScope())
      {
          var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
          // rest of your code
      }
      

      编辑

      正如 davidfowl 所说,这将在 2.0.0 RTM 中工作,因为将为 Configure 方法创建范围服务提供者。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-01
        • 1970-01-01
        • 2017-07-01
        • 2017-12-09
        • 1970-01-01
        • 1970-01-01
        • 2015-09-28
        • 1970-01-01
        相关资源
        最近更新 更多