concept idisposable in category .net

appears as: IDisposable
Dependency Injection in .NET

This is an excerpt from Manning's book Dependency Injection in .NET.

Because DEPENDENCIES may be shared, a single consumer can’t possibly control its lifetime. As long as a managed object can go out of scope and be garbage collected, this isn’t much of an issue, but when DEPENDENCIES implement the IDisposable interface, things become much more complicated.

In .NET, an object’s life cycle is simple: the object is created, used, and garbage-collected. The presence of IDisposable complicates things a bit, but the life cycle isn’t more complicated than that. When we discuss OBJECT LIFETIME, we talk about how we manage objects’ life cycles.

Let’s go back to the WCF service example from section 8.1.2. As it turns out, there is a bug in listing 8.2 because, as figure 8.9 shows, SqlProductRepository implements IDisposable.

Figure 8.9. SqlProductRepository implements IDisposable because it encapsulates a disposable resource. It also derives from the abstract ProductRepository class that doesn’t implement IDisposable.

How should an OrderService class deal with such a DEPENDENCY? Most design guidelines (including FxCop and Visual Studio’s built-in Code Analysis) would insist that if a class holds a disposable resource as a member, it should itself implement IDisposable and dispose of the resource like this: