简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM