views:

558

answers:

2

I'm using StructureMap in my project and when the application finishes running I need to call the Dispose() method on all of the instances inside the ObjectFactory that implement IDisposable.

I cannot find anyway to do it via the StructureMap API.

Another thought I had was to get a reference to every instance and call it myself, but I cannot figure out how to loop through all of the instances.

A: 

I've figured it out. Here is the code:

foreach (PluginTypeConfiguration pluginType in ObjectFactory.Model.PluginTypes)
{
    IList instances = ObjectFactory.GetAllInstances(pluginType.PluginType);
    foreach (object instance in instances)
    {
        if (instance is IDisposable)
        {
            ((IDisposable)instance).Dispose();
        }
    }
}
Stefan Moser
FYI - StructureMap does not hold instances in the container, unless they are marked as Singletons. The default behavior is to give you a new instance every time you ask for one. So your code above just creates a new instance of every type in the container, and then disposes that new instance.
Joshua Flanagan
True, however it is the Singleton objects that I'm worried about.
Stefan Moser
+1  A: 

PS: You might be interested in the deterministic disposal by Autofac IoC container

Autofac can guarantee that components are disposed of predictably.

Rinat Abdullin