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

Constructor Injection with StructureMap

DZone's Guide to

Constructor Injection with StructureMap

·
Free Resource

Last week I posted a quick introduction to dependency injection with a StructureMap.  I'd like to take that a step further and look at some other dependency injection techniques.  In the into, we looked at how to automatically fulfill an interface for a class.  What if we have a class that has a dependency on that interface?  You can use StructureMap to do "Constructor Injection".  It will look at the constructor of the class when creating an instance and see if there are any dependencies it can fulfill.  

We have our interface class from before:

public class RealStuff : IStuff
{
public string Name { get; set; }
public void DoStuff()
{
Console.WriteLine("Real Stuff");
}
}

Now we have a class that uses it:

public class ClassThatUsesStuff
{
public void ClassThatUsesStuff(IStuff stuff)
{
// Do Something with the stuff
}
}

We are using the same initialization logic:

ObjectFactory.Initialize(x =>
{
x.For<IStuff>().Use<RealStuff>();
});

The ClassThatUsesStuff has a constructor that takes an instance of IStuff so there are two ways we can fulfill it.

First we could just create an instance like we did in the intro and pass it in:

IStuff stuff = ObjectFactory.GetInstance<IStuff>();
ClassThatUsesStuff classThatUsesStuff = new ClassThatUsesStuff(stuff);

The stuff instance here will be an instance of RealStuff because of StructureMap.  While this works, we can use StructureMap to take a step out of the equation:

ClassThatUsesStuff classThatUsesStuff = ObjectFactory.GetInstance<ClassThatUsesStuff>();

What is happening here is that the GetInstance call looks at the class it is creating an instance of and sees that it is looking for an IStuff, which it is configured to provide.  It creates the new IStuff using the RealStuff concrete class and our new object is created as we wish.  The new RealStuff gets passed to the ClassThatUsesStuff constructor behind the scenes for you.  And that, is one of the beauties of dependency injection.

 

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 }}