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?
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.