我如何在 Net 6 中的程序中使用 DbInitializer

How can I DbInizializer in Program in Net6

我是 .net 的新手,我正在学习一门课程,但遇到的问题很少,我无法初始化我的 Db, 我有一些数据在程序启动时最先放入,我遇到了这个问题

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

和泰

恐怕你可以参考这个official tutorial:

将您的Initialize设置为静态方法,然后可以像您Program.cs中提到的教程那样调用它:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using MvcMovie.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<MvcMovieContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext")));

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    SeedData.Initialize(services);
}

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    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.UseAuthorization();

app.MapControllerRoute( 名称:“默认”, 模式:“{controller=Home}/{action=Index}/{id?}”);

app.Run();

app.Services.GetService<IDbInitializer>().Initialize();