If you’ve been keeping up with my blog, you know that I’ve been working on my wife’s new website. If you want to catch up, you can read the following previous posts:
- Refactoring my MVC & Photo Repository
- jQuery AJAX with ASP.NET MVC
- Beauty of Interfaces
- Learning Fluent NHibernate
So I wanted to share how I setup my StructureMap configuration. When I first started looking into StructureMap, I was a bit intimidated and I just want to assure you that it was unwarranted. StructureMap is a really friendly tool and easy to setup. I’m going to be using a class called DependencyRegistrar, which I basically stole from the sample code in the ASP.NET MVC in Action book. The only thing I modified was the RegisterDependencies method to add in my Registry. Once you get the DependencyRegistrar class, you’ll understand what I’m talking about.
Okay, so as I mentioned before, with StructureMap they give you a Registry class to inherit from so you can override the configure method. Here is my implementation:
public class DependencyRegistry : Registry
{
protected override void configure()
{
Scan(x =>
{
x.TheCallingAssembly();
x.WithDefaultConventions();
});
ForRequestedType<IPhotoRepository>()
.TheDefaultIsConcreteType<FlickrPhotoRepository>();
ForRequestedType<IMailingListSubscriber>()
.TheDefault.Is.OfConcreteType <FluentMailingListSubscriber>();
}
}
Basically what this says is scan the calling assembly and use the default conventions…which means if you see an interface called IDirectorySearcher, create a new instance of DirectorySearcher by default. Below the scan, I specify specific types because they don’t match the default convention. They did originally, but if you remember from my previous posts, I ended up re-implementing a couple things. As of right now, that’s all I have in my registry and it looks really simple and readable.
The only other thing I had to do was call the EnsureDependenciesRegistered method in the DependencyRegistrar I mentioned earlier in the Application_Start() of the global.asax. It looks like this:
DependencyRegistrar.EnsureDependenciesRegistered();
That’s it for the configuration and now I can call DependencyRegistrar.Resolve() to instantiate whatever class is needed! In the Learning Fluent NHibernate post, I called the Resolve method and it looked like this:
var subscriber = DependencyRegistrar.Resolve<IMailingListSubscriber>();
When I call Resolve, it returns the FluentMailingListSubscriber implementation. The main thing I like about any IoC tool is that it forces you to code to interfaces, which is always a good thing! Say I added a new method to the FluentMailingListSubscriber, but not the IMailingListSubscriber. I wouldn’t be able to use the new method because there is nothing there to let me know I can use it. So I have to define it in the interface…good stuff!
Please let me know your thoughts! Thanks for reading!