Felix C
Felix C

Reputation: 1775

Hold context in static class for all views or in concrete class?

I'm developing an asp.net MVC4 application using entity framework.

Should I hold the context of my entities in an static class to have only one point where to create my context or should I create the context in each controller?

And do I have to call Dispose() by myself or is it done safely from GC (like said in the second answer here: Should Entity Framework Context be Put into Using Statement? ).

If i decide to use the static class, is there a safe point to dispose the context variable ("the end of the application")?

Example of my static class:

public static class ApplicationHelper
{
    static ApplicationHelper()
    {
        Db = new ApplicationEntities();
    }

    internal static readonly ApplicationEntities Db;
}

Upvotes: 1

Views: 673

Answers (1)

Travis J
Travis J

Reputation: 82287

The context is not considered to be thread safe, so having it in a static variable is probably a bad idea. Also, the GC will call dispose on your context for you, when it wants to, at some distant point in the future after probably all of your connections are used up. In other words, explicitly call Dispose. This is commonly done using a using() statement.

All in all, you should either use a DI Container to inject your contexts and have the lifetime of the connection managed that way, implement a Unit Of Work pattern which will manage the context lifetimes via the repository pattern, or explicitly open and close your connection in the action methods of your controller.

public ActionResult SomeAction()
{
 using( var db = new ApplicationEntities() )
 {
  //todo: use db
 }
 return View();
}

Upvotes: 2

Related Questions