我正在尝试在我的Program.cs文件中,在.NET 6 minimal API模板下调用EF Core方法,并收到以下错误:
System.InvalidOperationException:'无法从根提供程序解析范围服务'Server.Infrastructure.DbContexts.AppDbContext''
// ************** 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
? - Hazrelle