1

I have following abstract class and need to implement IDisposable to make sure that DbContent will be disposed all the time properly.

public abstract class DataRepositoryBase<T> : DataRepositoryBase<T, MainDbContext>
    where T : class, IIdentifiableEntity, new()
{

}

what is the best way to achieve that?

Please NOTE: I'm greatly aware on how to use IDisposable in concrete classes but implementation of this functionality in the abstract class - not very clear

Yuri
  • 2,820
  • 4
  • 28
  • 40
  • 4
    [There are guidlines for that](https://msdn.microsoft.com/en-us/library/b1yfkh5e%28v=vs.110%29.aspx) – Jamiec Jul 17 '15 at 13:36
  • If it's abstract, why are you adding concrete functionality, like disposing of a database, to it? – David Arno Jul 17 '15 at 13:37
  • 2
    @DavidArno - cleaning up the resources created in an abstract class is the *right* thing to do! – Jamiec Jul 17 '15 at 13:38
  • @Jamiec, I'll take you word for it as I don't use abstract classes; I use interfaces. So it becomes the responsibility of implementing classes to decide for themselves whether they need to dispose of anything. – David Arno Jul 17 '15 at 13:40
  • 3
    @DavidArno You can use both interfaces **and** abstract classes. They serve different purposes under different circumstances. It absolutely makes sense to use an abstract class and implement `IDisposable` if the abstract class is implementing a significant body of boilerplate functionality that is then specialized by subclasses. Using an interface in that situation would result in duplicated code, violating DRY. I can't imagine why you would just disregard one language construct entirely. – Daniel Mann Jul 17 '15 at 14:45
  • @DanielMann, simple answer to that: I'd use composition rather than inheritance. I disregard inheritance because it's well recognised that it leads to complex, tightly coupled, difficult to test code. So in this case, I'd inject an implementation of eg IDbContent that uses IDispobable. – David Arno Jul 17 '15 at 14:53

1 Answers1

2

I would take the implementation provided in this answer:

Proper use of the IDisposable interface

And in derived types override the Dispose(bool disposing) method if the derived type needs to also dispose of stuff, remembering to call base. If it doesn't need to, then simply do nothing with the base implementation.

Make sure it makes sense to expose the need to call Dispose on this type's public contract, it could be a sign of a leaked abstraction (though not always).

This would at the very least be a good start.

Community
  • 1
  • 1
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187