Run cachewarmer on startup

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 someone using Daniels method, and if using scoped services like EF data context inside the cachewarm service, you will get below error.

'Cannot resolve 'ICacheWarmerService' from root provider because it requires scoped service 'dbContext'.'

For this you can create scope and use your cached method.

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();
}

Tags:

Asp.Net Core