How can I use dbInitializer.Initialize() in .NET 6.0;
Asked Answered
J

1

5

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.

Jovian answered 28/3, 2022 at 17:34 Comment(0)
L
8

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();
}
Leningrad answered 28/3, 2022 at 17:53 Comment(1)
second way work for me.Jovian

© 2022 - 2024 — McMap. All rights reserved.