Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run cachewarmer on startup

Tags:

asp.net-core

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.

like image 439
Trolley Avatar asked Oct 21 '16 09:10

Trolley


2 Answers

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();
    }
}
like image 64
Daniel J.G. Avatar answered Sep 28 '22 11:09

Daniel J.G.


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();
}
like image 33
Brad Avatar answered Sep 28 '22 10:09

Brad