Tuesday 23 August 2022

How can I DbInizializer in Program in Net6

 Problem:

Hey software developer team now I am using .NET 6  and I was following a course and I had little issue , that I can't initiliaze my Db, I have some data that most be put in first when program launch , and I hade this issue

IDbInitializer.cs

public interface IDbInitializer
{
    public void Initialize();
}

DbInitializer.cs

public class DbInitializer
{
    public void Initialize()
   {
     ............
   }
}

Program.cs


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.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();
dbInitialize.Initialize();<------ How can I call her here ?,

 because I keep getting error "Use of unassigned local variable 'dbInitializer'"

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
 
app.Run();


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

Solution:

Just you add some lines of codes here as shown in below:

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