In terms of an IoC container, my component of choice is StructureMap. Compared to other components available, StructureMap is purely IoC. Additionally, it can also be used without a configuration file.
I’ve been playing around with the ASP.Net MVC, namely in regards to its extensibility and how it can be simplified. I found that the MVCContrib project has already implemented StructureMap as an IoC container, but with a critical flaw – you have to register all of your concrete controller types individually! A much better solution would be similar to how they did the Windsor implementation, where each controller type is dynamically added to the container.
So I set out to do just that…only to end up spending way too much time running into dead ends. I found many resources on the interweb about using the StructureMap config file, but no where did I find the code-equivalent of the same thing. To further complicate the issue, the fluent interface of the StructureMapConfiguration class does not expose a way to send a concrete Type in – you could only do it via generics, which again defeats dynamically populating the container.
Finally, after scouring the StructureMap source code, I found a solution. The key to configuring the container is the IExpression interface. The following snippet shows an implementation that creates the controller plugin family, searches the assemblies in the bin directory for controllers, and adds them to the family as plugins.
Using a custom Registry class to introduce the custom expression, we can now do the following:
Now we’ve got StructureMap creating our controllers!
This sure seems like a lot of work just to be able to add plugin types dynamically. Hopefully future versions of StructureMap can address the configuration interfaces to allow types to be passed in rather than using generics.