I have ASP.NET Core Razor pages app and I would like to access IWebHostEnvironment
in my Program.cs
. I seed the DB at the beginning of the application, and I need to pass the IWebHostEnvironment
to my initializer. Here is my code:
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();
}
Because I have images in wwwroot
and I need to get names of of images from there during initializtion. I tried to pass IWebHostEnvironment
from Startup.cs inside of configure method:
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();
});
}
But it seems that the Startup.Configure
method gets executed after the Program.Main
method. Then I decided to do it in Startup.ConfigureServices
method, but it turns out that this method can only take up to 1 parameter. Is there any way to achieve this? However, I'm not sure that the way I'm trying to seed my data is the best one, I just see this way as the most appropriate for my case, so I would totally appreciate any other suggested approach.
Similar problems I found: