Tuesday 23 August 2022

How can I use dbInitializer.Initialize() in .net 6.0

 Problem:

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.



-----------------------------------------------------------------------------------------------------


Solution:


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


First Approach:


//By creating scope via ServiceProviderServiceExtensions.CreateScope:


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

Second Approach:


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



No comments:

Post a Comment