Reputation: 669
Context:
Question:
How can I load this data at initialization time, before HTTP requests start coming in? Do I do it in my controller's constructor? In my Startup.cs? I would appreciate some guidance here.
Thanks!
Upvotes: 0
Views: 1840
Reputation: 631
I would do this in Configure
method. Code should be something like this, then webapp will be available until data are pre-loaded.
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
//service should has been configured in ConfigureServices step
//Create method to check if data loaded. If not then load them.
serviceScope.ServiceProvider.GetService<ApplicationDbContext>().CheckDataLoaded();
}
//more steps here..
Upvotes: 1
Reputation: 1039120
If you want to ensure that this data is loaded before calling any code in your controllers, then you could put it in the Startup
class which is used for bootstrapping your application.
Upvotes: 1