Integrating MonoRail with your favorite IoC container

September 5th, 2008

I’m way outdated on my e-mail-reading and especially blog-reading. I don’t even read them anymore! I quickly scan them and try to get a gist… Someday people will actually emphasizes some words to make it easier for scanners like me to get the idea without stopping and reading every word ;-)

Anyway, I bumped into one of Jeremy’s post. Quoting:

“When we were deciding between Ruby on Rails, the ASP.Net MVC, and MonoRail for our project architecture in June, I dismissed MonoRail in small part because I didn’t want to be forced to use Windsor as our IoC tool (for some reason).”

Well, MR in no way forces you to use Windsor. For goodness’ sake, it’s on our mission page:

Castle should not be all-or-nothing. The developer can use the tools he wants to use, and at the same time, use different approaches in different areas of his application in a peaceful manner.

Of course, MR magically integrates with Windsor – what would you expect from us? But it can, just as well, magically integrates with any IoC container too.

So, what does it take to integrate MonoRail with your IoC container of choice?

First thing: MonoRail is made of several services. It had always used a composition-over-inheritance design principle that someone day more people will understand and adopt more – we’re always a decade behind, aren’t we?

(note to self: blog about all services that make the whole monster live).

So basically all you need to do is replace one or two services, depending on the level of integration you want. For the most basic integration, you might want to replace the controller factory and the filter factory by services implementation that know your IoC container (and knows how to access an instance of it). This can be made through the external monorail configuration (on the web.config) as described on the services article and on the configuration documentation.

A more complete level of integration, however, is something faily recent (10 months old I guess). Quoting an old post:

MonoRail now always uses the ServiceProviderLocator class to obtain a IServiceProvider and uses it as it’s parent container. That’s means that you can use any IoC container by simply making your HttpApplication class implement IServiceProvider (or better, IServiceProviderEx).

That means that MonoRail will always ask your code (the class that extends HttpApplication and is set on global.asax) before adding its default implementation of any of its services. That makes trivial to replace any service.

Note: I was actually going to provide a sample code but sorry, no time…

Leave a Reply