MVC Object Instances or Static Classes?

I am confused about when to instantiate objects or static helper classes. For example, if I call a method to update the data model and submit to the database, I create an instance of the DataContext. What is the lifetime of this Datacontext and is it okay to create new instances every time new data updates should appear?

In my controller, I created a DataCOntext instance and reused that instance when posting back to the controller.

0


source to share


1 answer


DataContext is a fairly lightweight class and is intended to be used in a unit of work. Typically, I pass the Factory, which will create the appropriate DataContext when needed. I usually wrap this in a use block and convert the results to a list (or other object) so that the request is executed in the controller code and the result objects passed to my view. Thus, the DataContext can be removed (from the used block) in the controller method.



The reason the Factory is injected into the controller is twofold - it allows me to create a DataContext on demand and allows me to use a Factory that generates a DataContext mock for testing. The latter allows me to avoid using the actual database in my unit tests.

+2


source







All Articles