1

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(); } } 
2
  • Who creates repository instances? Commented Jan 11, 2014 at 19:02
  • 1
    You should only implement a destructor/finalizer when you need to clean up UNMANAGED resources (such as handles, pointers to unmanaged stuff etc). And even then shouldn't you create a finalizer, but rather use the SafeHandle or a related class. So: noo! You don't need that finalizer. Commented Jan 11, 2014 at 19:10

5 Answers 5

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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?

Comments

0

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.

Comments

-3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.