3
votes

I'm using castle windsor 3.1.0.0 for dependency injection in my MVC 3.0 application.

My container is setup to provide controllers like this:

            container.Register(Classes.FromThisAssembly().BasedOn<IController>().LifestylePerWebRequest());

This seems to be working as I see a new controller instance created for every request. However according to the documenation: http://docs.castleproject.org/Windsor.LifeStyles.ashx, I must also place this in my web.config:

<httpModules>
   <add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor"/>
</httpModules>

which I don't have. What is the behavior of Castle Windsor if this module is missing? (The documentation says that In order to function properly per web request you must have this in your web config).

1

1 Answers

2
votes

As far as I understand, the PerWebRequestLifestyle requires an IHttpModule so that it can piggy-back off the init method and the HttpApplication events such as BeginRequest.

The reason why everything seems to be working is because the module has been initialised and so the PerWebRequestLifestyle is functioning normally.

But why is that the case if you didn't include the registration module? I suspect that it is a legacy instruction and that the container will attempt a registration on its own, but this isn't documented explicitly.

If we take a peek inside CastleWindsor we find something called Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModuleRegistration. It has this method:

public static void Run()
{
    Type type = Type.GetType("Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility, Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", false);
    if (type == null)
    {
        return;
    }
    MethodInfo method = type.GetMethod("RegisterModule", BindingFlags.Static | BindingFlags.Public);
    if (method == null)
    {
        return;
    }
    object[] objArray = new object[] { typeof(PerWebRequestLifestyleModule) };
    method.Invoke(null, objArray);
}

What is DynamicModuleUtility? A quick search reveals a page written by K. Scott Allen called DynamicModuleUtility.

The DynamicModuleUtility will let you install an HTTP module into the ASP.NET pipeline without making any changes to web.config file.

This is only my speculation as to what's going on. You'd have to ask the creators of Castle Windsor for details on exactly how things are working.