[英]How to access DbContext in .NET 6 minimal API Program.cs
I am trying to call EF Core methods on application startup in my Program.cs file, using the .NET 6 minimal API template and get the following error:我正在尝试使用 .NET 6 最小 API 模板在我的 Program.cs 文件中调用应用程序启动时的 EF Core 方法并得到以下错误:
System.InvalidOperationException: 'Cannot resolve scoped service 'Server.Infrastructure.DbContexts.AppDbContext' from root provider.'
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();
}
// ...
With earlier versions of .NET Core I am aware I can get the DbContext in the Configure
method, but how would I get the service with this approach?使用早期版本的 .NET Core 我知道我可以在
Configure
方法中获取 DbContext,但是如何使用这种方法获取服务?
Scoped services require scope to be resolved.范围服务需要解决scope 。 You can create scope via
ServiceProviderServiceExtensions.CreateScope
:您可以通过
ServiceProviderServiceExtensions.CreateScope
创建 scope :
using(var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// use context
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.