views:

95

answers:

2

Hi,

I am using Factory pattern to create .NET objects of a class. I also need to make sure that all such objects should be disposed before application terminates.

Where and How can I dispose the objects created by factory pattern? Shall I dispose in the class in which I am getting the objects created by factory?

+5  A: 

Why do you want to dispose them before the application terminates? Is this because they hold unmanaged resources?

If this is the case, just implement IDisposable and perform the cleanup in the Dispose method, and let .Net take care of the rest.

Gerrie Schenck
They do not hold any unmanaged resources. I need to dispose those objects to clear the memory.
Ram
.Net does this for you as soon as the application ends.
Gerrie Schenck
.Net will dispose of these objects once the objects are no longer being used (there is nothing referencing them). This can be and often is way before the application ends!
Mongus Pong
Thanks a lot. :)
Ram
+3  A: 

When your factory creates new IDisposable objects, the caller should normally dispose such an object. An advisable pattern is the following:

using (var instance = Factory.CreateInstance(someArg))
{
    // use the instance
}

When your Factory uses some internal pool, then it is still advisable to let the caller dispose the object, but in that case, as soon as the instance is disposed, it should be returned to the pool. However, such a design is much more complicated.

Steven