A longstanding complaint with StructureMap is that the way StructureMap selects a constructor function can only be overridden with an attribute. Using attributes is now frowned upon, and other times is impossible. StructureMap 2.5.2 (the version in the trunk that, knock on wood, I get released no later than Saturday) introduces a quick programmatic way to select the constructor function using the magic of Expressions. This is an excerpt from the new StructureMap documentation I’m working up. It will be much more readable on the website (next week hopefully):
StructureMap has always allowed you to override the constructor choice with an attribute, but increasingly, many people are unwilling to use attributes in their code for infrastructure concerns. Other times you may want to override the constructor choice of a class that you don’t control. Either way, it would be useful to select the constructor function used by StructureMap to build a concrete code in the Registry DSL. The syntax to do just that is shown below:
Let’s say that you have this class (from the unit tests):
public class ClassWithTwoConstructors
{
public ClassWithTwoConstructors(int age, string name)
{
}
public ClassWithTwoConstructors(int age)
{
}
}
By default, StructureMap would choose the “greediest” constructor. In this case, it would be the constructor that takes in “age” and “name.” To force StructureMap into using the other constructor, use the SelectConstructor() method on the Registry:
var container = new Container(x =>
{
x.SelectConstructor<ClassWithTwoConstructors>(()=>new ClassWithTwoConstructors(0));
x.ForConcreteType<ClassWithTwoConstructors>().Configure
.WithCtorArg(“age”).EqualTo(34);
});
The argument to the SelectConstructor is an Expression of type Expression<Func<T>> where T is the concrete class. StructureMap parses the Expression to find the constructor function in the Expression object.