Property Injection with StructureMap
Join the DZone community and get the full member experience.
Join For FreeA few weeks back, I gave an introduction to dependency injection with StructureMap and then showed how to use it to do constructor injection. In most cases, I use constructor injection, but there are some cases where I need a parameter-less constructor so my only option is to use a property. StructureMap supports this but you have to add a little bit more code to make it work.
Just for review, here is the interface class from previous articles:
Just for review, here is the interface class from previous articles:
public class RealStuff : IStuffAnd the class that uses the interface but as a property instead of a constructor:
{
public string Name { get; set; }
public void DoStuff()
{
Console.WriteLine("Real Stuff");
}
}
public class ClassThatUsesStuffI will be using the same initialization logic as I have previously:
{
public IStuff Stuff { get;set; }
}
ObjectFactory.Initialize(x =>It's pretty cool because I don't have to change my initialization logic or even the code that gets the instance of a concrete class:
{
x.For<IStuff>().Use<RealStuff>();
});
IStuff classThatUsesStuff = ObjectFactory.GetInstance<ClassThatUsesStuff>();Now if I run the above code, it won't work because StructureMap doesn't pick up properties quite as easily as it does constructors. To make it work all we have to do is simply tag the property with a StructureMap [SetterProperty] attribute:
public class ClassThatUsesStuffIf I run the code to get the concrete class, the property will be injected just as I would expect. This does come with a caveat; The ClassThatUsesStuff, now has to carry a dependency on StructureMap itself, which may not be desired depending on your situation. It requires us to add a #using statement for StructureMap.Attributes. It is this reason why I tend to lean more towards constructor injection over property injection. If you don't mind carrying the extra dependency, then this method will work fine and I do have several projects where I use a combination of both. It really boils down to what your individual needs are and if you asked which method I would recommend, I would have to give the classic developer answer of "It depends". I do tend to prefer constructor injection, but when the scenario requires, property injection is a perfect alternative.
{
[SetterAttribute]
public IStuff Stuff { get;set; }
}
Dependency injection
Property (programming)
Opinions expressed by DZone contributors are their own.
Comments