1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

13 Comments

So placing private ApplicationDbContext context = new ApplicationDbContext(); at the controller level will create an instance on every request? will that instance be disposed after the server responds?
No you should write a dispose method on your controller to dispose of the context. That's another convenience thing with the other technique.
won't I have to manually dispose of the context anyway before returning from an action?
Controllers implement IDisposable already. All you need to do is override it with your own implementation and call the base method.
So by creating an instance of the context like this: var context = HttpContext.GetOwinContext().Get<ApplicationDbContext>(); I don't need to dispose of it explicitly?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.