Skip to main content

Dependency Injection With Sitecore Webforms and StructureMap

Unlike most posts on this blog I guess this isn't really Sitecore specific. But I'm writing it in direct response to to an article written last year by Sitecore guru Kevin Obee, so I think it's still relevant.

In his post, Kevin notes the lack of dependency injection in most Sitecore webforms solutions, and wonders why this might be. I admit I always assumed proper DI was impossible with user controls because they need parameterless constructors. I also didn't know where you could intercept the request to resolve dependencies. Service location was an option, but seeing Resolve<ISomething>() littered throughout an application always makes me a little bit annoyed. I just don't think it adds much value.

So I was intrigued when Kevin demonstrated that DI in Sitecore webforms solutions was not only possible, but easy using AutoFac. I immediately went to check if the equivalent functionality existed in our container of choice, StructureMap.

It's not...

So I spent a rainy Sunday afternoon wading through the AutoFac source code trying to write my own version. I ended up with something quite neat that works very well. It's a simple HTTP module that resolves the types of public setters just before the page_load event on any user control.

All you need to do is add a reference to this class in the httpModules section of your web.config or alternatively use a PreApplicationStartMethod.

Happy injecting!


Related Links

Mark Cassidy also wrote a response to Kevin Obee's post on DI: Setup Castle Windsor for Sitecore 8.1 in 5 easy steps

After eventually finding my way to a working solution I discovered that somebody else has written something very similar for Unity.

Comments