Given it’s reached v1.0 I finally decided to do some work with the ASP.NET MVC framework and what better way than to take the Issue Tracker which currently runs on Rhino Igloo and refactor it to run on ASP.NET MVC, so expect the next few posts to be related to my findings of how to get things done with it.
First thing is that Rhino Igloo out of the box handles controller creation and uses Castle Windsor to do this ASP.NET MVC by default will use it’s own controller builder, because of this it expects your controllers to have a default no-arg constructor this is no good as I have controllers that need their dependencies passed in, so we need to replace the default controller builder with a version that we can hook up to Castle Windsor.
Now I could go and write my own version this is because the framework is very flexible and was built to allow you to plugin your own objects, in this case an object that implements
IControllerFactory will suffice however why re-invent the wheel when the guy’s over at MvcContrib have done most of the work for us.
Getting the MvcContrib Objects
Head over to to the MvcContrib project on codeplex and grab the extras release, now copy the MvcContrib.dll and MvcContrib.Castle.dll into your external references folder and add a reference where you will be doing the app startup.
Setting the Controller Factory
global.asax or wherever you do app startup you need to add the following code:
ControllerBuilder.Current.SetControllerFactory( new WindsorControllerFactory(this.Container));
Notice that I’m passing the current instance of the windsor container which I get for free because I’m using the
UnitOfWorkApplicationbase class from
Rhino.Commons, you will probably have some custom way of managing your container, in which case it just needs to be passed in to the constructor of
Wiring up the Controllers
Next we need to make Windsor aware of the controllers, I use Binsor for my Windsor configuration this gives me a nice way to autowire new controllers to Windsor without making any changes:for type in AllTypes("IssueTracker.Controllers"): continue unless typeof(IController).IsAssignableFrom(type) component type.Name, type: @lifestyle="transient"
Gotta love the conditional expression support Boo has to offer it almost reads like a sentence 🙂 You could also use the XML configuration or programmatic configuration to configure your controllers, and that’s all there is to it!
Kudos to the ASP.NET team for having the foresight to allow these kind of extensions to be plugged in so easily and also to the MvcContrib contributer’s for creating this and support for other IoC containers out there.Advertisements