views:

65

answers:

2

I have this code.

A base class that create a new instance of the context.

public class Base
{
      private Entities context;

      public Base()
      {
            context = new Entities();
      }
}

And than the classes that inherit from this class.

public class SomeService : Base
{

      public Gallery Get(int id)
      {
           return context.GallerySet.FirstOrDefault(g => g.id == id);
      }
}

The question is,how to take care of disposing the context object ? I was thinking about a destructor in the base clas, where I would just call the dispose method of the context object.

~Base()
{
    context.Dispose();
}

Would be this enough ? Or is there any other way to take care of the context object ?

+6  A: 

Your Base class should implement IDisposable rather than having a finalizer. You should only have a finalizer when you have direct access to unmanaged resources (e.g. an IntPtr representing a Windows handle).

However, I would try to work out a design which didn't involve this. Wherever possible, I try to avoid having member variables which need disposing - I tend to acquire resources within methods, pass those resources to other methods, and then dispose of them within the same method that acquired them. The fewer implementations of IDisposable you have, the less resource lifetime complexity you're likely to have to manage. Obviously sometimes it's unavoidable...

Jon Skeet
It does make sense what you said about IDisposable.But with the approach above I wanted get rid of calling using in every method like thisusing(Entities context = new Entities()){ ....}The class SomeService will have alot of short methods using the context object. And the repetition of the using approach in every method is against the SOLID principe.
You'll still need using statements somewhere though. You don't need the using statement in each SomeService method - the context could be passed into the method instead, for example.
Jon Skeet
Agree with @Jon. Have a look at [this article][1].Note that the title is Implementing Finalize and Dispose to Clean Up **Unmanaged Resources**, even if the article is categorised under Common Design Patterns (disposable pattern)[1]: http://msdn.microsoft.com/en-us/library/b1yfkh5e%28VS.71%29.aspx
Neil Fenwick
@Jon I can't imagine how could be this done. Could you please provide a simple example ? Thx in advance
Which bit don't you understand? You just pass the context into the method as an argument. The caller can create one context and pass it to different methods.
Jon Skeet
And what about if the methods are called over WCF (namedpipes) ?
+1  A: 

Having the destructor as you wrote it would be actually wrong, because the framework doesn't guarantee that the context object is going to be valid at the point of finalizing.

You should implement IDisposable on your object and dispose the context there. If the context have unmanaged resources, it should have a finalizer of its own.

Grzenio