Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Property Injection with StructureMap

DZone's Guide to

Property Injection with StructureMap

·
Free Resource
A 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:
public class RealStuff : IStuff
{
public string Name { get; set; }
public void DoStuff()
{
Console.WriteLine("Real Stuff");
}
}
And the class that uses the interface but as a property instead of a constructor:
public class ClassThatUsesStuff
{
public IStuff Stuff { get;set; }
}
I will be using the same initialization logic as I have previously:
ObjectFactory.Initialize(x =>
{
x.For<IStuff>().Use<RealStuff>();
});
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:
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 ClassThatUsesStuff
{
[SetterAttribute]
public IStuff Stuff { get;set; }
}
If 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.
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}