开发者

How-to do the clean up?

I have this code.

A base class that create a new instan开发者_运维问答ce 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 ?


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...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜