我有一个ASP.NET Core Razor页面应用程序,我想在Program.cs
中访问IWebHostEnvironment
。 我在应用程序开始时播种DB,并且我需要将IWebHostEnvironment
传递给我的初始化程序。 这是我的代码:
Program.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
目录中有一些 图片,并且我需要在初始化期间从那里获取这些图片的名称。我尝试在 Startup.cs 中的 configure 方法中传递 IWebHostEnvironment
:
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
方法中完成,但是这个方法只能接受一个参数。有没有办法实现这个目标?不过,我不确定我正在尝试种植数据的方式是否是最佳的,我只是认为这种方式最适合我的情况,所以我非常感谢任何其他建议的方法。类似的问题:
IHostedService
中完成所有播种操作,在应用程序运行时执行所需的作用域功能。 - Nkosi