我有一个ASP.NET Core MVC应用程序,并在服务容器中有一个CacheWarmerService。目前我只使用内存缓存,但我需要在应用程序启动时运行它。
但是,我对如何做到这一点表示怀疑。我的CacheWarmerService有一些需要在构造函数中注入的服务。我可以从Startup.cs类中执行此操作,或者将它放在何处?
它需要在每次启动时运行。
您还可以创建自己漂亮而干净的扩展方法,例如app.UseCacheWarmer()
,然后您可以从Startup.Configure()
调用:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
... logging, exceptions, etc
app.UseCacheWarmer();
app.UseStaticFiles();
app.UseMvc();
}
在该方法中,您可以使用app.ApplicationServices
访问DI容器(IServiceProvider
)并获取所需服务的实例。
public static class CacheWarmerExtensions
{
public static void UseCacheWarmer(this IApplicationBuilder app)
{
var cacheWarmer = app.ApplicationServices.GetRequiredService<CacheWarmerService>();
cacheWarmer.WarmCache();
}
}
您可以在Configure
的Startup
方法中注入您的服务(以及任何其他服务)。
此方法中唯一需要的参数是IApplicationBuilder
,如果在ConfigureServices
中配置了任何其他参数将从DI注入。
public void Configure(IApplicationBuilder app, CacheWarmerService cache)
{
cache.Initialize(); // or whatever you call it
...
app.UseMvc();
}
如果有人使用Daniels方法,并且如果在cachewarm服务中使用像EF数据上下文这样的范围服务,则会出现以下错误。
'Cannot resolve 'ICacheWarmerService' from root provider because it requires scoped service 'dbContext'.'
为此,您可以创建范围并使用缓存方法。
public static void UseCacheWarmer(this IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.CreateScope())
{
var cacheWarmer = serviceScope.ServiceProvider.GetService<ICacheWarmerService>();
cacheWarmer.WarmCache();
}
//// var cacheWarmer = app.ApplicationServices.GetRequiredService<ICacheWarmerService>();
//// cacheWarmer.WarmCache();
}