Fork me on GitHub

Object Lifecycles Edit on GitHub


One of the most valuable functions of using an IoC container tool is its ability to manage the object lifecycle (creating and disposing objects) and scoping (shared objects) of your system's services so you can focus on the actual functionality instead of busy work.

Some services like data cache's and event aggregators in your system will need to be shared across requests, screens, and handlers. Other services should be created new every time you ask the container for one. Another set of services need to be scoped to an HTTP request or a logical transaction such that every request to the container for a service originating within the context of a single HTTP request gets the same object instance.

In all the cases above, StructureMap will assemble object graphs for you using the correct scoping of each dependency. Likewise, in some cases, StructureMap can help you with object cleanup by calling IDisposable.Dispose() as appropriate when an object lifecyle is completed.

Motivation for Container Managed Scope

In the bad old days, we used the infamous Singleton pattern as shown below for objects that really needed to be scoped as one single instance for the entire system:


public class EvilSingleton
{
    public static readonly EvilSingleton Instance = new EvilSingleton();

    private EvilSingleton()
    {
    }

    public void DoSomething()
    {
        // do something with the static data here
    }
}


public class EvilSingletonUser
{
    public void DoWork()
    {
        EvilSingleton.Instance.DoSomething();
    }
}

The code above isn't terribly difficult to write or understand, but using a Singleton has some negative effects on your code as explained in Singletons are Evil and my own writing at Chill out on the Singleton Fetish.

Instead, let's just use StructureMap to handle the singleton scoping instead and rewrite the code sample above as:


public class SingletonService { }

public class SingletonUser
{
    public SingletonUser(SingletonService singleton)
    {
    }
}

public class SingletonScopeRegistry : Registry
{
    public SingletonScopeRegistry()
    {
        For<SingletonService>().Singleton();
    }
}

The big advantage to the second, StructureMap-managed singleton scoping is that my DependencyUser class does not have to have any knowledge of how the ISingletonDependency object is built and certainly no coupling to the hard Singleton mechanics from the first sample that was so harmful in the past.