我该如何在.NET 6.0中使用dbInitializer.Initialize()?

5

这就是.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 中无法使用了。请问该怎么办?请帮忙解决。

1个回答

8

根据的注册方式,您应该能够直接从中解决它:

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();
}

第二种方法适合我。 - rasoul fetrati

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接