【发布时间】: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,但是如何使用这种方法获取服务?
【问题讨论】:
-
抛出的错误是什么?您是否尝试过先创建一个作用域
app.Services.CreateScope(),然后在作用域上调用GetService?
标签: c# entity-framework-core .net-6.0 minimal-apis