Fork me on GitHub

Custom Lifecycles Edit on GitHub


Lifecycles in StructureMap are pluggable. To create your own custom lifecycle, make an implementation of the ILifecycle interface like this one:


public class CustomLifecycle : ILifecycle
{
    public static LifecycleObjectCache Cache = new LifecycleObjectCache();

    public string Description
    {
        get { return "Custom"; }
    }

    public void EjectAll(ILifecycleContext context)
    {
        // Here you'd remove all the existing objects
        // from the cache and call IDisposable.Dispose()
        // as appropriate
    }

    public IObjectCache FindCache(ILifecycleContext context)
    {
        // using the context, "find" the appropriate
        // IObjectCache object
        return Cache;
    }
}


Registering your custom lifecycle can be done like this:


public class UsingCustomLifecycle : Registry
{
    public UsingCustomLifecycle()
    {
        // at the Plugin Type level
        For<IService>().LifecycleIs<CustomLifecycle>();

        // at the Instance level
        For<IService>().Use<AService>()
            .LifecycleIs<CustomLifecycle>();
    }
}


Most of the built in ILifecycle implementations use LifecycleObjectCache internally, but you may also need to create your own IObjectCache implementation.