1

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).

Tallmaris
  • 7,605
  • 3
  • 28
  • 58
  • "Repo and DbContext here seem to be instantiated as singletons, which in a sense is expected." - I think that you should instantiate a new DbContext on each request. See http://stackoverflow.com/questions/9415955/c-sharp-working-with-entity-framework-in-a-multi-threaded-server/9416275#9416275 – Ofiris Jul 15 '14 at 08:56
  • Hi Ofiris, that is exactly the condundrum. To do that I would need to clear and add the ViewEngine at every request and my problem is if this can cause too much overhead. – Tallmaris Jul 15 '14 at 08:59
  • Does `AreaAwareRazorEngine` implements `IViewEngine` directly or inherits other implementation? – haim770 Jul 15 '14 at 10:26
  • Good question! I am inheriting `RazorViewEngine` and only overriding the `FindPartialView` method (basically I am simply adding locations to the `AreaPartialViewLocationFormats` and `PartialViewLocationFormats` arrays). – Tallmaris Jul 15 '14 at 11:33

0 Answers0