Kishore Kumar
Kishore Kumar

Reputation: 12864

Should I use Destructor when I inherit from IDisposable?

I am creating a ServiceLayer for my EntityFramework.

The service layer uses the Repositories which implements IDisposable. Since I am not implementing IDisposable in my Service class, should I use the Destructor to dispose object, or they will be automatically disposed by GC.

public class ProductService
{
    private readonly ProductRepository _productRepository;

    public ProductService(ProductRepository repo)
    {
        _productRepository = repo;
    }

    ......
    ......

    ~ProductService()
    {
        _productRepositort.Dispose();
    }

}

Upvotes: 1

Views: 316

Answers (5)

Dennis
Dennis

Reputation: 37760

Since I am not implementing IDisposable in my Service class, should I use the Destructor to dispose object

You must not call IDisposable.Dispose in finalizer, because it is intended for unmanaged resources cleanup. And, after appearance of SafeHandle, you should consider using SafeHandle instead of implementing finalizer.

You must call IDisposable.Dispose elsewhere, because GC doesn't call Dispose, when it frees object's memory. The place and the moment, when you'll call Dispose, depends on who, where and when creates IDisposable implementation.

Usually, Dispose is called by the object, who was created IDisposable.

Upvotes: 2

Matt Greer
Matt Greer

Reputation: 62027

Disposing has nothing to do with the garbage collector. It's more about closing database connections, file handles, etc.

If you are using something that is disposable, your class should be disposable too and dispose of those items using the dispose pattern

Upvotes: 4

Softlion
Softlion

Reputation: 12585

See the IDisposable pattern here http://msdn.microsoft.com/en-US/library/b1yfkh5e(v=vs.110).aspx

Upvotes: -3

Sergey Litvinov
Sergey Litvinov

Reputation: 7458

If you are using IoC that creates this ProductService and that ProductRepository has some LifeTime, then that IoC should call DisposeproductRepository. It's usefull for Web Application and when lifetime is set to just one HttpRequest.

If you use ProductRepository without using keyword or you don't call Dispose method manually, then Dispose won't be called by GC. GC will call just destructor, and it doesn't call Dispose method.

Upvotes: 0

realnero
realnero

Reputation: 994

The answer depends on the scope of the reposytory instance. Where is it created and for how long object is available. Or do you register repository with DI?

Upvotes: 0

Related Questions