Tom Gordon
Tom Gordon

Reputation: 545

ASP.NET Web API Startup Questions

I am creating an ASP.NET Web API using .NET 4.5.2. The API needs to connect to a runspace on startup. I have questions about when this Startup.Configuration method actually runs though. It does not seem to run when I start the website or app pool. It seems to wait until the first time somebody tries to access the website. Is this correct? Also, it seems to run again at random times. I have seen it run after 2 hours, 4 hours, and 16 hours. It doesn't really make any sense. Can somebody clear up for me when these methods should run? Also, if you have a suggestion for a better place to put them given that I want it to be a shared runspace for all connections and that I want it to run before anybody tries to connect to the API. Perhaps a separate service?

Also, would it be worth looking into ASP.NET CORE? I don't need it to run on anything other than IIS, however if there is a benefit to using CORE I am at a point where it will be easy to switch.

public partial class Startup
{
    public Cache GlobalCache;
    public static PowershellRunspace PSRunspace;
    public static ActiveDirectory ADObjects = new ActiveDirectory();
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        GlobalCache = new Cache();
        AppLog log = new AppLog();

        log.InfoLog("Starting PowerShell Runspace in Hangfire...", true);

        GlobalConfiguration.Configuration.UseSqlServerStorage("Hangfire");
        BackgroundJob.Enqueue(() => log.InfoLog("Hangfire started!", true));
        BackgroundJob.Enqueue(() => ADObjects.Startup(true));
        BackgroundJob.Enqueue(() => StaticRunspace.Start());

        app.UseHangfireDashboard();
        app.UseHangfireServer();

    }
}

Upvotes: 0

Views: 681

Answers (1)

Haney
Haney

Reputation: 34802

Assuming you're running this application in IIS (and not self-hosting), the following rules apply:

  1. The Configuration method runs once per application start.
  2. The application is started lazily (on the first request to it via HTTP/S).
  3. IIS has a few settings that affect the application:
    1. An idle timeout. If the app isn't accessed via a request in 20 minutes then the application is unloaded / put offline. The next request starts it again.
    2. A regular app pool recycle. It just straight up restarts the application by recycling the app pool every 1740 minutes.

So the behavior you're seeing is likely due to the infrequent access of the application, combined with the IIS defaults. If you'd like to see or configure the settings, you can do so by going into IIS, right clicking on your app pool, and selecting Advanced Settings.

Upvotes: 1

Related Questions