Question

Looking at some of the MVC examples online, I've see that typically in a controller the DbContext variable is declared as a private member variable (i.e. global) and accessible to all the methods.

But, I recently came across an article on ASP.NET Identity, and noticed in the controller, the DbContext is declared within each method (that requires it).

Is there a security benefit to this approach? Perhaps limit the lifespan of the security object(s) for better overall security?!?!

If not, then I see the first approach being more efficient, where the database context is instantiated upon the controller loading.

Below is all I could find about DbContext, but nothing to really answer my question.

DbContext declaration - Framework 4.1 - MVC 3.0

MVC, DbContext and Multithreading

Était-ce utile?

La solution

On every request, a new instance of the controller is constructed. Therefore, for all intents and purposes, it does not really matter whether the dbcontext is instantiated in the constructor vs encapsulated in any given method.

Aside from a style choice, reasons to declare and contain a dbcontext in a given method is that:

  • Methods that do not need it will not instantiate the context, eliminating the overhead (if there is any). This can also be accomplished using a lazy initialization pattern.
  • The context is disposed of immediately as soon as a method is done with it, rather than at the end of the request. Generally this should not be a concern though; usually if users are waiting around for longer than a few seconds you have a bigger problem.
  • Different methods use different contexts.

Among others, some reasons to declare a single context and instantiate it once:

  • You have only one place that instantiates a context rather than many. In a typical application, most pages will need some information from the database anyway.
  • Methods that call other methods will not each hold on to their own instance of a context object.
  • You can create a base controller class that by default creates a dbcontext object, allowing you to be DRY in all inherited controllers.

Autres conseils

Answer from @Ic. is pretty good. I wanted to add that if you need to pass information from your Request into your DbContext constructor then you need to create the instance of your DbContext inside your action methods. The reason is the Request object will be null till the control enters your action method.

More information: I had a need to build connection string dynamically depending on the location of the user. I saved the location as a cookie that I accessed through Request object. I had a valid Request inside the action method but it was null inside the constructor or at the class level properties of the controller.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top