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.