Dependency Injection with StructureMap

posted @ Wednesday, May 31, 2006 8:19 PM

 

I have posted previously about using Spring.NET as an IoC container and how we can implement some of this out of the box with the System.ComponentModel namespace. StructureMap is another dependency injection framework that in my opinon is much more approachable than Spring out of the box. Why? - Let's take a look at what it takes to start requesting services from the StructureMap container.

 

IRule rule = ObjectFactory.GetInstance<IRule>();
or for .NET 1.1

 

IRule rule = ObjectFactory.GetInstance(typeof(IRule)) as IRule;
To begin with, StructureMap now supports generics (granted the 1.0.2 release of Spring does as well), however what is important is I didn't have to create an IResource to initialize an XmlObjectFactory to begin requesting services (again there are some shortcuts in Spring as well but lets continue on). Custom backing stores can be defined for the configuration by deriving from MementoSource in StructureMap. Something that I think is important to note here is that if you aren't using generics, you will request a particular service via a Type, which is different from Spring in which you provide a string as the look up key within the configuration. In my opinion this is nice as it gives me compile time confirmation that I am requesting a type that exists, whereas I could possibly misspell the string if I were using Spring and the compiler wouldn't skip a beat.

Another nice aspect about StructureMap is the ability use attributes to decrease the amount of configuration data that needs to be stored within an XML file. One of the major complaints with Spring is the excess configuration information. This also allows for code to be refactored without making changes to the configuration file. Also, configuration data can be broken up into several config files or even stored as embedded resources. StructureMap comes with StructureMapExplorer as well as StructureMapDoctor to help diagnose problems. I did have to apply the [STAThread()] attribute to the Main method for the StructureMapExplorer code, without that, an instance of the AxWebBrowser could not be created and the application would crash. Since they are targetting .NET 2.0, maybe they will consider using the new WebBrowser class? Overall Jeremy Miller and Jeffrey Palermo have created a very nice product, well worth checking into for your next design.