How to automatically call a function after pool recycling on IIS

I would like to know-how in my web app written in C#.NET5 (+React) call function after IIS server use setting for recycling Web data on IIS -> Application Pool -> Recycling (Regular Time Interval (In Minutes)) set on 1440.

I load over 6 GB to memory (IMemoryCache) and it takes over 6 minutes then all data is loaded, I would like to call the load function to cache automatically after each cycle of the recycling period, before waiting for the user interaction.

I try it call in StartUp, in Main, and also with use IHostetServices, but in each case, I got an error then called service (my class with load method) is not recognized

3 Ways to Run Code Once at Application Startup in ASP.NET Core


I got these errors: when I try to call

{"Unable to resolve service for type Repository.DataFilters.Static.IGroupLoader' while attempting to activate 'Search.Startup'."}

When I try to call:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");               
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();

        // Add other security headers
        app.UseMiddleware<SecurityHeadersMiddleware>();

        
        app.UseSerilogRequestLogging();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";

            var isDev = env.EnvironmentName.Contains("Dev");

            if (env.IsDevelopment() || isDev)
            {
                spa.UseReactDevelopmentServer(npmScript: "start");
            }
        });

        _GroupLoader.LoadGroupFiltersToMemory(); // try to call this method from my class

    }

In ConfiguredService:

    private readonly IGroupLoader _GroupLoader;

    public Startup(IConfiguration configuration, IGroupLoader groupLoader)
    {
        Configuration = configuration;
        _GroupLoader = groupLoader;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddMemoryCache();

        // DB Contexts
        services.AddDbContext<GroupContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        // Services
        services.AddScoped<IGroupService, GroupService>();

        // Repositories
        services.AddScoped<IGroupLoader, GroupLoader>();

        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/build";
        });
    }

enter image description here

This solution does not work:

<system.webServer>
            <aspNetCore xdt:Transform="SetAttributes(startupTimeLimit)" startupTimeLimit="300">
            </aspNetCore>
        </system.webServer>

After IIS runs Recycling, Its looks like the App is not loaded, I must do an initial run like the open website link, is it possible to load the app automatically after the recycling process of IIS?

In Startup.cs I am not able to call await functions Called function take over 8 minutes, then all data was loaded

Looks like then I must use: https://docs.microsoft.com/en-us/iis/get-started/whats-new-in-iis-8/iis-80-application-initialization#TOC301259895


Update 09.01.2022

After I set IIS and App to autostart I got this error:

enter image description here

I try to do this: https://serverfault.com/questions/590865/how-can-i-warm-up-my-asp-net-mvc-webapp-after-an-app-pool-recycle

In web.config I set:

<applicationInitialization
    remapManagedRequestsTo="Startup.html" 
    skipManagedModules="true" >
  <add initializationPage="/subpage" />
</applicationInitialization>
  1. Then when I try to call page /subpage (without using Startup.cs -> Configure call of IMemoryCache function), the function to load into IMemoryCache is not called, but when I run the app with Visual Studio or deploy an app to IIS without autostart (warmup), a function is called.

  2. When I try to call function (with load IMemoryCache) via Startup.cs -> Configure function, the function is called but IIS server start many (10-11 process) IIS Worker Process and I got error upper, also Startup.html webpage is not called during the loading process (I am not sure where must be located in .NET 5 Core Web App with React Solution).

I got this error:

System.InvalidOperationException: Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

This was maybe caused by many IIS Worker processes which calls the same function (in IMemoryCache loading function I have use lock())

Thank you


You can't inject your IGroupLoader dependency into your Startup.cs before the depedency injection has been setup - this is described by the error you provided.

According to this guide, you can inject a dependency in Configure once you've setup dependency injection in ConfigureServices.

i.e. you need to change:

from

 private readonly IGroupLoader _GroupLoader;

 public Startup(IConfiguration configuration, IGroupLoader groupLoader)
 {
     Configuration = configuration;
     _GroupLoader = groupLoader;
 }

to

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

from

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

to

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IGroupLoader groupLoader)

from

_GroupLoader.LoadGroupFiltersToMemory();

to

groupLoader.LoadGroupFiltersToMemory();