I've been trying to use LightInject in an ASP.NET MVC 4 app, and uncovered something that's got me scratching my head. My code looks like this:
public class MvcApplication : System.Web.HttpApplication {
private ServiceContainer container;
protected void Application_Start() {
RouteConfig.RegisterRoutes(RouteTable.Routes);
container = new ServiceContainer();
container.Register<IUserStore, MyUserStore>(new PerScopeLifetime());
container.EnableMvc();
}
protected void Application_AuthenticateRequest() {
var users = container.GetInstance<IUserStore>();
/* Do some stuff here! */
}
}
Application_AuthenticateRequest
is blowing up because container is null. Now, in the past I've always made things like the IOC container static, but never really stopped to consider why... so I tried making container
a regular instance field, and BOOM! nothing works.
So I tried putting a parameterless constructor on MvcApplication
with a Debugger.Break()
inside it, and it looks like IIS is instantiating the application, running Application_Start
, destroying that instance, then instantiating another one to handle the first incoming request. Is this by design? I had always assumed IIS would instantiate your application once and run it until it was shut down or the pool was recycled... but I realise now I have no idea where I got this idea from. The MSDN documentation says "The first time that an ASP.NET page or process is requested in an application, a new instance of the HttpApplication class is created. However, to maximize performance, HttpApplication instances might be reused for multiple requests" - which suggests ASP.NET might actually destroy and instantiate application instances arbitrarily. Is this the case? And - if so - am I right in thinking that I should just use static fields for anything (like my IoC container) that needs to be instantiated during Application_Start
and then available to all subsequent requests?