Yoav
Yoav

Reputation: 3386

Handling Entity-Framework Context

In the new MVC-5 template there's a file at the App_Start folder called Startup.Auth.cs which contains this lines (along with some other data):

// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

What does a single instance per request meen? and what is the difference between calling the ApplicationDbContext like this:

var context = HttpContext.GetOwinContext().Get<ApplicationDbContext>();

and placing this declaration as a field in the Controller class:

public class HomeController : Controller
{
    private ApplicationDbContext context = new ApplicationDbContext();

Is there a preferred approach for handling the context? is a singleton class providing the context preffered?

Upvotes: 1

Views: 253

Answers (1)

jimSampica
jimSampica

Reputation: 12420

It's just a convenient way of having a context object created whenever one of your action methods are called. You want a single instance per request because you want all of your objects to be attached to the same context instance. You also want the lifetime of your context to be the request lifetime.

If you were to use the second approach private ApplicationDbContext context = new ApplicationDbContext(); you would have to put that into every controller. You could create some sort of base controller that does the same thing and just inherit from your base controller.

Again it's just a convenience method used for demonstration.

Upvotes: 1

Related Questions