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:
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.
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!