When we use an IoC tool the most basic functionality we expect is to have constructor injection. That means if we have a type we are resolving and one of the constructor’s parameters is also a type, the container will resolve that type as well.
And turtles all the way down…
If we have two types(Foo : IFoo and Bar : IBar) and in Bar’s constructor it has an IFoo parameter, we should expect the IFoo parameter to be resolved to an instance of Foo.
Our container is setup like :
We then expect :
Sometimes you need to specify the exact argument for a given type when it is constructed. Structure Map allows you to provide specific values for resolving a constructors argument.
For example, Ryan was asking if there is a method with SM to resolve an “id” value from an HttpContext. I know SM has some fancy session management lifecycle features built in, but since I don’t live in the Web world I have never explored what can and can not be done with those features.
What I do know is that I can specify where my “id” parameter comes from.
Let’s look at this simple example.
In my scenario I have a Foo class.
The id that is passed into Foo is providing by some mysterious X. In my case my X is an IIdProvider.
Now I want to tell SM that when it resolves an IFoo, I want it to use the IIdProvider to get the “id”.
All together the configuration is:
And my tests to verify it works:
Lazy Constructor Arguments
Then Ryan tells me, he would really like to be lazy because he might not need the id for all requests. There are some Lazy features added to SM 2.6 but let’s just use what we already know to solve this problem.
Instead of having an int Id parameter, let’s have a Func<int> getId parameter.
Foo changes to :
Now our constructor configuration changes to :
And our tests become :
Yes it is a poor man’s lazy instantiation. But in many ways its the clearest way to have the functionality.
You can find all this code in my Git Hub Learning Repository and the Learning Structure Map solution : http://github.com/RookieOne/Learning