如何在.NET 6最小API程序.cs中访问DbContext



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

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,但如何使用这种方法获得服务?

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

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

相关内容

最新更新