gpt4 book ai didi

c# - 如何从 ASP.NET Core 中的 Program.cs 访问 IWebHostEnvironment

转载 作者:行者123 更新时间:2023-12-04 12:33:11 25 4
gpt4 key购买 nike

我有 ASP.NET Core Razor 页面应用程序,我想访问 IWebHostEnvironment在我的 Program.cs .我在申请开始时给数据库做种,我需要通过 IWebHostEnvironment到我的初始化程序。这是我的代码:
程序.cs

public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();

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

try
{
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}

host.Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
SeedData.cs
    public static class SeedData
{
private static IWebHostEnvironment _hostEnvironment;
public static bool IsInitialized { get; private set; }

public static void Init(IWebHostEnvironment hostEnvironment)
{
if (!IsInitialized)
{
_hostEnvironment = hostEnvironment;
IsInitialized = true;
}
}

public static void Initialize(IServiceProvider serviceProvider)
{
//List<string> imageList = GetMovieImages(_hostEnvironment);

int d = 0;

using var context = new RazorPagesMovieContext(
serviceProvider.GetRequiredService<
DbContextOptions<RazorPagesMovieContext>>());

if (context.Movie.Any())
{
return; // DB has been seeded
}

var faker = new Faker("en");
var movieNames = GetMovieNames();
var genreNames = GetGenresNames();

foreach(string genreTitle in genreNames)
{
context.Genre.Add(new Genre { GenreTitle = genreTitle });
}

context.SaveChanges();

foreach(string movieTitle in movieNames)
{
context.Movie.Add(
new Movie
{
Title = movieTitle,
ReleaseDate = GetRandomDate(),
Price = GetRandomPrice(5.5, 30.5),
Rating = GetRandomRating(),
Description = faker.Lorem.Sentence(20, 100),
GenreId = GetRandomGenreId()
}
);
}

context.SaveChanges();
}
因为我有 图片 wwwroot我需要在初始化期间从那里获取图像的名称。我试图通过 IWebHostEnvironment来自 Startup.cs 配置方法内部:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
int d = 0;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/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();
}

SeedData.Init(env); // Initialize IWebHostEnvironment
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
但似乎 Startup.Configure方法在 Program.Main 之后执行方法。然后我决定在 Startup.ConfigureServices做方法,但事实证明该方法最多只能接受 1 个参数。有没有办法实现这一目标?但是,我不确定我尝试为数据播种的方式是最好的方式,我只是认为这种方式最适合我的情况,因此我非常感谢任何其他建议的方法。
我发现的类似问题:
  • Use IWebHostEnvironment in Program.cs web host builder in ASP.NET Core 3.1
  • Issues with getting wwwroot folder using IWebHostEnvironment in asp.net core 3.1 web api
  • How can I get access to the IWebHostEnvironment from within an ASP.NET Core 3 controller?
  • 最佳答案

    最初的问题展示了如何尝试将 DI 与静态类一起使用会导致比它解决的问题更多的问题。
    播种机可以是一个范围内的注册类,并在构建后从主机解析。可以通过构造函数注入(inject)显式注入(inject)宿主环境和任何其他依赖项
    例如

    public class SeedData {
    private readonly IWebHostEnvironment hostEnvironment;
    private readonly RazorPagesMovieContext context;
    private readonly ILogger logger;

    public SeedData(IWebHostEnvironment hostEnvironment, RazorPagesMovieContext context, ILogger<SeedData> logger) {
    this.hostEnvironment = hostEnvironment;
    this.context = context;
    this.logger = logger;
    }

    public void Run() {
    try {
    List<string> imageList = GetMovieImages(hostEnvironment); //<<-- USE DEPENDENCY

    int d = 0;

    if (context.Movie.Any()) {
    return; // DB has been seeded
    }

    var faker = new Faker("en");
    var movieNames = GetMovieNames();
    var genreNames = GetGenresNames();

    foreach(string genreTitle in genreNames) {
    context.Genre.Add(new Genre { GenreTitle = genreTitle });
    }

    context.SaveChanges();

    foreach(string movieTitle in movieNames) {
    context.Movie.Add(
    new Movie {
    Title = movieTitle,
    ReleaseDate = GetRandomDate(),
    Price = GetRandomPrice(5.5, 30.5),
    Rating = GetRandomRating(),
    Description = faker.Lorem.Sentence(20, 100),
    GenreId = GetRandomGenreId()
    }
    );
    }

    context.SaveChanges();
    } catch (Exception ex) {
    logger.LogError(ex, "An error occurred seeding the DB.");
    }
    }

    // ... other code

    }
    请注意不再需要 Service Locator 反模式。所有必要的依赖项都根据需要显式注入(inject)到类中。 Program然后可以简化
    public class Program {
    public static void Main(string[] args) {
    var host = CreateHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope()) {
    SeedData seeder = scope.ServiceProvider.GetRequiredService<SeedData>();
    seeder.Run();
    }
    host.Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureServices(services => {
    services.AddScoped<SeedData>(); //<-- NOTE
    })
    .ConfigureWebHostDefaults(webBuilder => {
    webBuilder.UseStartup<Startup>();
    });
    }
    在运行主机之前,播种机向主机注册并根据需要解析。现在无需访问除播种机以外的任何内容。 IWebHostEnvironment所有其他依赖项将由 DI 容器解析并在需要的地方注入(inject)。

    关于c# - 如何从 ASP.NET Core 中的 Program.cs 访问 IWebHostEnvironment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67027277/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com