Sunday, April 26, 2009

Using Windsor IoC in ASP.NET MVC

With the power of an IoC engine, you can inject your repositories, services, etc. when building applications using ASP.NET MVC framework. Since one of the best IoC engines out there IMHO is Castle Windsor using it has become natural more than ever, but as soon as I did, strange problems occurred when testing very simple scenarios. Two major pains were:

Model Binders
ModelBinders automatically bind form values to your object properties. When using Windsor, I noticed that almost all the parameter values are null when passed to the controller action.

Parameter Values
When a controller action was called with a parameter for the first time, all subsequent calls somehow cached the parameter values. Type and Value of the parameter has no effect, and even disabling caching didn’t work.

I’ve been pulling my hair for a couple of days (yeah, I kinda went bald because of this) before I figure this out, and when I thinking about it, the reason of this behavior is clearly obvious!

Windsor uses Singleton lifetime for registered services. All you need to do when registering controllers, is to use Transient lifetime!

Container.Register(AllTypes.FromAssemblyContaining<MvcApplication>()
.Where(o => o.Namespace == typeof(HomeController).Namespace)
.Configure(o => o.LifeStyle.Is(LifestyleType.Transient)));

Problem solved, Case closed!


Submit this story to DotNetKicks Shout it

1 comment:

Ryan Hartzog said...

Thank you for this post. I have been having problems with these two items as well. Changing the registering lifestlye to transient solved the "chaching" of action parameters, but not my model binding issue. Did you discover any other pieces of information that would lead to the model not to be bound automagically?