views:

177

answers:

1

I am confused as to when to create object instances or Static Helper classes. For example, if I call a method to update a data model and submit to database, i create an instance of the DataContext. What is the lifetime of that Datacontext and is it ok to create new instances every time there needs to be a new data updates?

In my controller I created an instance of DataCOntext and reuse that instance when posting back to controller for example.

+2  A: 

The DataContext is a pretty lightweight class and is intended to be used for a unit of work. Typically, I pass in a Factory that will create an appropriate DataContext as needed. I will usually wrap this in a using block and convert the results to a List (or other object) so that the query is performed in the controller code and the resulting objects passed to my view. This way the DataContext can be disposed of (from the using block) in the controller method.

The reason that inject a factory into the controller is two-fold -- it allows the DataContext to be created on demand and it allows me to use a factory that generates a mock DataContext for testing. The latter allows me to avoid using the actual database in my unit tests.

tvanfosson
Thanks. Is there something wrong with creating one Datacontxt in the controller class and having all the ActionResults share it?
zsharp