【问题标题】:How to access DbContext in .NET 6 minimal API Program.cs如何在 .NET 6 最小 API Program.cs 中访问 DbContext
【发布时间】:2021-12-16 22:29:13
【问题描述】:

我正在尝试使用 .NET 6 最小 API 模板在我的 Program.cs 文件中调用应用程序启动时的 EF Core 方法并收到以下错误:

System.InvalidOperationException: 'Cannot resolve scoped service 'Server.Infrastructure.DbContexts.AppDbContext' from root provider.'

// ************** Build Web Application **************

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(configuration.GetConnectionString("AppDb:Postgres")));

// ...

// **************** Web Application *****************

var app = builder.Build();

var dbContext = app.Services.GetService<AppDbContext>(); // error thrown here

if (dbContext != null)
{
    dbContext.Database.EnsureDeleted();
    dbContext.Database.Migrate();
}

// ...

对于早期版本的 .NET Core,我知道我可以在 Configure 方法中获取 DbContext,但是如何使用这种方法获取服务?

【问题讨论】:

标签: c# entity-framework-core .net-6.0 minimal-apis


【解决方案1】:

Scoped 服务需要解析范围。您可以通过ServiceProviderServiceExtensions.CreateScope 创建范围:

using(var scope = app.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    // use context
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 2022-06-14
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多