StructureMap and the Singleton Scenario

A few months ago I made the switch from CastleWindsor to StructureMap for my dependency injection needs. It’s a more active project, more up to date with the times, more extensible, and definitely has a better interface for configuring through code rather than xml. After a few growing pains I’ve grown to like it a lot ( I’m using version 2.5). However in the last few days I’ve run into a roadblock it seems, and it all has to do with the lifecycle/scope of objects.

A lot of dependency objects in the typical application could be singletons if designed right (covers head from flames). However there is a point at which that ceases to be the case, that’s where unit of work patterns come into play. A unit of work has only a finite lifespan and should then be disposed. In keeping with good testability and design patterns you will probably also want to have a ready made unit of work object injected into the classes that need them. Every time that you ask for a unit of work you should be supplied with a fresh new copy. That’s where configuring the lifecycles properly in your DI tool should come into play.

As code is a common language, I will code out what I am talking about as simply as possible.

//Think of this as a data session
public class Session
{
}
 
public class Model1
{
    public Session Session { get; set; }
 
    public Model1(Session session)
    {
        Session = session;
    }
}
 
public class Model2
{
    public Session Session { get; set; }
 
    public Model2(Session session)
    {
        Session = session;
    }
}
 
//this is my shell, it needs some models
public class Shell
{
    public Model1 Model1 { get; set; }
    public Model2 Model2 { get; set; }
 
    public Shell(Model1 model1, Model2 model2)
    {
        Model1 = model1;
        Model2 = model2;
    }
}

This is a pretty straight forward scenario. We have a shell (entry point) that contains a couple of models, each of these models requires a unique data session so that it can pull and work with its data independently.

Let’s use StructureMap to wire these together so that we just create our shell and have its dependencies filled for us automatically. Remember that by default StructureMap does not create singletons, so using the default config should result in transient, per-request objects.

ObjectFactory.Initialize(
    x => {
             x.BuildInstancesOf()
                 .TheDefaultIsConcreteType();
             x.BuildInstancesOf()
                 .TheDefaultIsConcreteType();
             x.BuildInstancesOf()
                 .TheDefaultIsConcreteType();
             x.BuildInstancesOf()
                 .TheDefaultIsConcreteType();
    });

Now let’s test to make sure that we have a unique data session.

Shell shell = ObjectFactory.GetInstance();
 
Assert.AreNotEqual(shell.Model1.Session, shell.Model2.Session);

And this is where we come to the fail part. The data session contained in each model is identical, the same as if we had declared it as a singleton. We know that the configuration is right because doing it this way works.

Assert.AreNotEqual(ObjectFactory.GetInstance(), ObjectFactory.GetInstance());

Why this happens has been a matter of great curiosity to me, and even though I’m not a great StructureMap expert I’ll hazard an educated guess. Each time that you make a declarative request for the root of an object graph, StructureMap creates a unique BuildSession. Inside that build session there is a cache of instantiated objects. The session then builds one object for each dependency in the graph no matter how many times it is requested in that graph. The objects may be built or pulled using a variety of methods but once they are built and stored in the graph then they are not requested to be built again for the lifetime of that BuildSession. This means that for a given declarative request you will only ever have one object per type instantiated. If, like me, you are starting your application from a bootstrapper this effectively turns all of your objects into singletons.

Lets try the same scenraio in CastleWindsor.

WindsorContainer container = new WindsorContainer();
 
container.AddComponentWithLifestyle("Session", typeof(Session), LifestyleType.Transient);
container.AddComponentWithLifestyle("Model1", typeof(Model1), LifestyleType.Transient);
container.AddComponentWithLifestyle("Model2", typeof(Model2), LifestyleType.Transient);
container.AddComponentWithLifestyle("Shell", typeof(Shell), LifestyleType.Transient);
 
Shell shell = container.Resolve();
 
Assert.AreNotEqual(shell.Model1.Session, shell.Model2.Session);

This works, both data sessions are unique. Let’s try AutoFac.

var builder = new ContainerBuilder();
 
builder.Register().FactoryScoped();
builder.Register().FactoryScoped();
builder.Register().FactoryScoped();
builder.Register().FactoryScoped();
 
var container = builder.Build();
 
Shell shell = container.Resolve();
 
Assert.AreNotEqual(shell.Model1.Session, shell.Model2.Session);

Again this works as well.

How can this problem be solved by mere mortals? Well the most obvious solution would be to pass factories that can create your transient objects instead of just passing the transient objects themselves. However this is not ideal as it just leads to more code noise that should be handled by the DI component.

Can we use an interceptor? Unfortunately this approach does not work as your custom interceptor will be called only once per BuildSession resulting in the same problem. The same is true for using a ConstructorInstance. As this post ends I have been searching for a way of getting true instanced objects out of structuremap for most of a day with no success. In ending let me say that I am open to any expertise you may offer on this subject, and if I do find the answer I will most definitely post an update to this article.

Update
It would appear that there is no good way to do this using StructureMap. There is a workaround that though arduous could work for more limited scenarios. The trick is to define the dependency for the object that needs a transient type.

x.BuildInstancesOf()
    .TheDefault.Is.OfConcreteType().CtorDependency().Is( x.OfConcreteType() );

Though this works it wouldn’t be really practical if your dependency is used in numerous places. The reasons that the author chose to limit transients to only once per session are valid and advantageous for his situation but causes some problems elsewhere. What I would have preferred was that the BuildSession caching was done with an interceptor the same way as singleton caching. That way not every instance would be limited by the BuildSession caching and other implementations could be provided.

Update

As Bart Deleye pointed out in the comments the latest version of StructureMap now properly supports this scenario with the following syntax.

.ForRequestedType().TheDefaultIsConcreteType().AlwaysUnique()

Thus resulting in a very happy ending due to the flexibility and collaborative nature of open source software.  Thanks Jeremy

kick it on DotNetKicks.com

7 Responses to “StructureMap and the Singleton Scenario”

  1. Garry Shutler Says:

    You can alter the lifecycle of each individual dependency. As you say the default is on per request but you can configure StructureMap to give you a new instance every time.

  2. Daniel Guenter Says:

    @Garry, can you post a sample on how this is done. I’ve tried every way I can think of, even something as basic as this, with no success.

    x.BuildInstancesOf()
    .TheDefault.IsThis(new Session());

  3. Garry Shutler Says:

    I’m away this weekend so I’ll have to get back to you on Monday I’m afraid.

  4. Steinar Dragsnes Says:

    You should also check out Spring.Net, if you do not like xml-configuration then you can also do it programmatically. I usually extend those classes I feel produce too much xml, so that I can specify the same logic in one or two lines of xml. The really nice thing with xml is that you can change some settings when you are at a customer’s site, without any form for redeployment.

    This would make a call to the object factory always create a new instance of the ClassName class in Spring.Net.

    Cheers,
    Steinar.

  5. Steinar Dragsnes Says:

    Seems like the example got lost in wordpress magic:

    [object id="Id" type="NameSpace.ClassName, Assembly", singelton="false" /]

    Replace [] with html brackets.

  6. Bart Deleye Says:

    One way to fix this is:
    .ForRequestedType().TheDefaultIsConcreteType().AlwaysUnique()

  7. Daniel Guenter Says:

    @Bart
    Thank you for pointing this out. This is actually a result of a patch I submitted for structuremap but I just hadn’t gotten around to updating this post.

    http://codebetter.com/blogs/jeremy.miller/archive/2009/02/01/structuremap-2-5-3-is-released-and-the-future-of-structuremap.aspx

Leave a Reply