带有 PerWebRequest 生活方式的工厂方法

Factory Methods with PerWebRequest lifestyle

我正在使用 Castle Windsor 并尝试使用 LifestylePerWebRequest。但是,我需要使用工厂方法来创建我的对象,所以我有以下注册。

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

当我在 CreateMyComponent 中放置一个断点时,我发现它在单个请求中命中了好几次。这看起来不像是 PerWebRequest 生活方式的正确行为。两者不兼容?我在这里做错了什么?

Castle 自己的 documentation 使用带有工厂方法的网络请求生活方式,因此它们应该兼容。

该部分的其余部分继续讨论使用 PerWebRequest 时的其他注意事项,因此可能值得一读。特别是:

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>

抱歉,如果这没有太大帮助!如果你得到正确的配置等等,看起来你想做的事情应该得到支持

尝试将此添加到您的 Global.asax.cs 文件以验证每个 Web 请求是否多次调用 CreateMyComponent(不应):

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

在 CreateMyComponent 方法和 Application_BeginRequest-method 中放置一个断点。调试器应该首先在 Application_BeginRequest-method 处停止,然后在 CreateComponent 方法处停止。它不应该再次进入 CreateComponent 方法,除非它首先进入 Application_BeginRequest-method。

也许您有一些 ajax 或其他资源可以生成多个请求 "per page load",从而使 Windsor 看起来像是在每个 Web 请求中多次调用您的工厂方法。这将告诉您是否是这种情况。

如果它确实在每个 HTTP 请求中多次调用您的方法,则可能是其他答案所建议的缺少配置。