A StructureMap Gotcha

I started converting one of the projects I work on to use the StructureMap DI/IOC framework. The previous framework I used was a super simple one that was built in house.   When switching to StructureMap the plethora of options was a concern at first but once I started the conversion I was amazed how easy it went.  However, there was one subtle difference between the behavior of the old framework I used and StructureMap around object lifecycle.

By default, the old framework created a new instance of an object every time it encountered its corresponding interface in a given object graph. I had assumed that was the same behavior StructureMap would use but I was wrong. StructureMap’s default is called PerRequest.

So when you just write this:


It will create a new instance of Thing only once per object graph.  What that means is if in a given graph with 3 classes that all have IThing in their constructor they will all receive the same instance of the Thing object.

This is an  issue since I have a couple classes that unfortunately have mutable state and do not behave well if the same instance is used. To fix this I just needed to tell StructureMap to always use a unique instance:

For<IThing>().LifecycleIs(new UniquePerRequestLifecycle()).Use<Thing>();

I personally think this should be the default behavior and any instance reuse should be specifically declared instead. At least it was easy enough to change.

Related Links