IDisposable Part 4 – Factored Types
For part 4 of my series on IDisposable, I wanted to mention one other place where this interface should be used – Factored Types.
Often, there will be a class hierarchy where a simplified interface should be provided which acts as a facade over an entire complex set of operations. The framework design guidelines provide a short sample of this with a SerialPort class.
The idea here is that, any time you are working on a set of operations in which you need to Close() something after Open(), or End() after a Start(), you’re basically acquiring a resource. This may not be a native resource in the traditional sense, but it still requires some form of cleanup.Â
In these situations, it helps to wrap this facade into a class that implements IDisposable. One of the best examples of this is the TransitionScope class added to .NET 2.0. This is meant to be used specifically to avoid having to start and stop a transaction – instead, you create the TransactionScope, which implements IDisposable, and use it in a using block so that the rollback is guaranteed if the commit does not occur (via scope.Complete()).
There is a great sample of this in the MSDN page on Implementing an Implicit Transaction.
In many ways, this acts like a C# or .NET version of Resource Acquisition Is Initialization (RAII). You acquire your resource (in this case, the TransactionScope) in a using statement, and the transaction is cleaned up when you exit scope.