Constructor Injection
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.
1 2 3 4 5 6 7 8 9 |
|
Our container is setup like :
1 2 3 4 5 6 7 |
|
We then expect :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Constructor Arguments
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.
1 2 3 4 5 6 7 8 9 10 11 |
|
The id that is passed into Foo is providing by some mysterious X. In my case my X is an IIdProvider.
1 2 3 4 5 6 7 |
|
Now I want to tell SM that when it resolves an IFoo, I want it to use the IIdProvider to get the “id”.
1 2 3 |
|
All together the configuration is:
1 2 3 4 5 6 7 8 9 |
|
And my tests to verify it works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
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
Foo changes to :
1 2 3 4 5 6 7 8 9 10 11 |
|
Now our constructor configuration changes to :
1 2 3 |
|
And our tests become :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
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