上下文:
问题:
如何在HTTP请求开始进入之前的初始化时加载此数据?我是否在控制器的构造函数中执行此操作?在我的Startup.cs中?我很感激这里有一些指导。
谢谢!
答案 0 :(得分:1)
如果要在调用控制器中的任何代码之前确保已加载此数据,则可以将其放在用于引导应用程序的{{1}}类中。
答案 1 :(得分:1)
我会在Configure
方法中执行此操作。代码应该是这样的,然后webapp将可用,直到数据被预加载。
// 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..