I'm having a problem trying to understand what happens to the DbContext being initialised (by an IoC container) during the Application_Start.
The application is a MVC4 with EF using Repositories, with Unity as IoC container. The situation is as follows in the Global.asax
:
protected void Application_Start()
{
// usual MVC init code, routes, bundles etc.
var container = Bootstrapper.Initialise();
ViewEngines.Engines.Clear();
var ve = container.Resolve<AreaAwareRazorEngine>();
ViewEngines.Engines.Add(ve);
}
The AreaAwareRazorEngine
is not registered in the container. This engine needs to use the DbContext to do its job. Repo and DbContext here seem to be instantiated as singletons, which in a sense is expected.
The DbContext is registered in Unity with a PerRequestLifetimeManager
so during normal browsing of the site it gets created and disposed when serving requests.
The problem I am having is that in the elmah log files I can see a lot of errors related to the usual "The DbContext has been disposed..." and I am guessing that what happens is that the GC may (in certain conditions) do a pass and dispose of the singleton Repository+DbContext.
A solution I was thinking about was to put the ViewEngine registration in the Application_BeginRequest
but I wanted to ask the community if this is a good practice or if can cause problems later on. I have no way of testing things locally since everything works normally and the problem is only when deployed to production (which begs the question if it's something that can be changed at IIS level).