I have an ASP.NET Core MVC application and have a CacheWarmerService in the service container. Currently I just use an in memory cache, but I need it to be run when the application starts up.
However, I'm in doubt on how to do it. My CacheWarmerService has some services that needs to be injected in the constructor. Can I do that from the Startup.cs class, or where should this be placed?
It needs to be run every time it starts.
You could also create your own nice and clean extension method like app.UseCacheWarmer()
that you could then call from Startup.Configure()
:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
... logging, exceptions, etc
app.UseCacheWarmer();
app.UseStaticFiles();
app.UseMvc();
}
Inside that method you can use app.ApplicationServices
to access to the DI container (the IServiceProvider
) and get instances of the services that you need.
public static class CacheWarmerExtensions
{
public static void UseCacheWarmer(this IApplicationBuilder app)
{
var cacheWarmer = app.ApplicationServices.GetRequiredService<CacheWarmerService>();
cacheWarmer.WarmCache();
}
}
You can inject your service (and any other service) in the Configure
method of Startup
.
The only required parameter in this method is IApplicationBuilder
, any other parameters will be injected from DI if they've been configured in ConfigureServices
.
public void Configure(IApplicationBuilder app, CacheWarmerService cache)
{
cache.Initialize(); // or whatever you call it
...
app.UseMvc();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With