我有一个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();
}
Run Code Online (Sandbox Code Playgroud)
在该方法中,您可以使用app.ApplicationServices
访问DI容器(the IServiceProvider
)并获取所需服务的实例.
public static class CacheWarmerExtensions
{
public static void UseCacheWarmer(this IApplicationBuilder app)
{
var cacheWarmer = app.ApplicationServices.GetRequiredService<CacheWarmerService>();
cacheWarmer.WarmCache();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在Configure
方法中注入您的服务(和任何其他服务)Startup
.
此方法中唯一需要的参数是IApplicationBuilder
,如果已经配置了DI,则会从DI中注入任何其他参数ConfigureServices
.
public void Configure(IApplicationBuilder app, CacheWarmerService cache)
{
cache.Initialize(); // or whatever you call it
...
app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3138 次 |
最近记录: |