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

Time:03-29

THIS IS .NET 5 i use IDbInitializer dbInitializer in public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IDbInitializer dbInitializer) now in .net 6 i cant do this job.

   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?}");
            });
        }

AND THIS IS .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();

AND I CANT USING dbInitializer.Initialize() LIKE BEFORE I USE IN .NET 5.0 I WANT USE IT IN .NET 6.0

HOW CAN I DO THAT? PLEASE HELP ME.

CodePudding user response:

Depending on how IDbInitializer is registered you should be able to either resolve it directly from app.Services:

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

Or by creating scope via ServiceProviderServiceExtensions.CreateScope:

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