0
votes

I'm using Castle Windsor and trying to use LifestylePerWebRequest. However, I need to use a factory method to create my object, so I have the following registration.

Component.For<IMyComponent>()
         .UsingFactoryMethod(CreateMyComponent)
         .LifestylePerWebRequest()

When I put a breakpoint in CreateMyComponent, I see it hit several times during a single request. This does not seem like the correct behavior of a PerWebRequest lifestyle. Are the two not compatible? What am I doing wrong here?

2

2 Answers

1
votes

Try to add this to your Global.asax.cs file to verify that the CreateMyComponent is called multiple times per web request (it should not):

protected void Application_BeginRequest(object sender, EventArgs args)
{
    System.Diagnostics.Debug.WriteLine(this.Request.RequestType + " " + this.Request.RawUrl);
}

Put a breakpoint in both the CreateMyComponent-method and the Application_BeginRequest-method. The debugger should first stop at the Application_BeginRequest-method, then at the CreateComponent-method. It should not go into the CreateComponent-method again unless it enters the Application_BeginRequest-method first.

Perhaps you have some ajax or other resources that generates multiple requests "per page load", thereby making it seem like Windsor invokes your factory method multiple times per web request. This will tell if that is the case.

If it is indeed invoking your method multiple times per HTTP request, it could be a lack of configuration as the other answer suggest.

0
votes

Castle's own documentation uses a web request lifestyle with factory methods, so they should be compatible.

The rest of that section goes on to discuss other considerations when using PerWebRequest, so might be worth a read. In particular:

We have to open our web.config file, find its system.web section, and there add the following:

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

Sorry if that's not much help! Still it looks like what you want to do should be supported if you get the right configuration, etc.