我如何在 .net 6.0 中使用 dbInitializer.Initialize();

how can i use dbInitializer.Initialize() in .net 6.0;

这是 .NET 5 我在 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IDbInitializer dbInitializer) 中使用 IDbInitializer dbInitializer 现在在 .net 6 中我无法完成这项工作。

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IDbInitializer dbInitializer)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseIdentityServer();
            app.UseAuthorization();
            dbInitializer.Initialize();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

这是 .NET 6.0

var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.MapRazorPages();

app.Run();

并且我不能像在 .NET 5.0 中使用之前那样使用 dbInitializer.Initialize() 我想在 .NET 6.0 中使用它

我该怎么做? 请帮助我。

根据 IDbInitializer 的注册方式,您应该能够直接从 app.Services:

解析它
var dbInitializer = app.Services.GetRequiredService<IDbInitializer>();
// use dbInitializer
dbInitializer.Initialize();

或者通过 ServiceProviderServiceExtensions.CreateScope 创建作用域:

using(var scope = app.Services.CreateScope())
{
    var dbInitializer = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
    // use dbInitializer
    dbInitializer.Initialize();
}