【发布时间】:2021-07-05 16:45:21
【问题描述】:
我有 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方法做,结果发现这个方法最多只能取1个参数。有什么办法可以做到这一点?但是,我不确定我尝试播种数据的方式是不是最好的方式,我只是认为这种方式最适合我的情况,所以我非常感谢任何其他建议的方法。
我发现的类似问题:
【问题讨论】:
-
这似乎是一个XY problem 并且有点过度设计。它还演示了如何尝试将 DI 与静态类一起使用会导致比它解决的问题更多的问题。您的播种器可以是一个作用域注册类,并在构建后从主机解析,通过构造函数注入显式注入主机环境。另一种方法可能是在
IHostedService中完成所有播种,在应用程序运行时执行您所需的作用域功能。 -
感谢@Nkosi 的建议,我查看了
XY problem,发现它非常有用。
标签: c# asp.net-core dependency-injection development-environment