I’ve had doing Structure Map posts on my To-Do list for a long time now. It is time to spring clean these items and get some posts up!
Like my other learning posts / projects, you can find the code at : http://github.com/RookieOne/Learning
I don’t want to dive into how / why you can use a DI / IOC tool like StructureMap. Or why SM over another IoC tool. So I won’t. :)
My recommendation is prefer to use a tool made by people who think about the problem the same way you do. You will be happier and self-discover features more easily.
I like the way Jeremy Miller thinks and naturally love Structure Map.
Normal Registration
Previously to register an interface with a concrete type there was a fluent by extremely verbose interface. With 2.6 that has been greatly simplified for a For
1 2 3 4 5 6 7 8 9 10 |
|
Singleton Registration
To register the type as a singleton, we just need to add a Singleton() call between our For and Use calls.
1 2 3 4 5 6 7 8 9 10 11 |
|
Open Generic Registration
One of the cool things with StructureMap is the ability to register open generics. I know other tools support this, but it is still cool. So in this test I am registering an open generic interface IRepository<> with a concrete yet still open generic implementation Repository<>. I can then asked for a IRepository
1 2 3 4 5 6 7 8 9 10 |
|
Open Generic with Closed Generic Alternative
Now this is where things get real cool. Besides registering an open generic concrete implementation, I can also registered a closed generic alternative. So in my test I am registering Repository<> for all IRepository<>. But I am also registering CustomerRepository with IRepository
So with this I can have a general implementation but then provide specific implementations for those exceptional cases.
1 2 3 4 5 6 |
|
Now for the tests pay close attention to the request to the container. Notice how the user of the container doesn’t need to know if the implementation they are using is the generic or the specific alternative. Isn’t that sweet!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Naturally there are tons of other things Structure Map does but this was just a brief intro to some of the basics. I plan on blogging a bit more on some of the other neat features that make SM my IoC tool of choice.