【问题标题】:Autofac adaptation for Castle Windsor温莎城堡的 Autofac 改编
【发布时间】:2013-09-30 12:15:31
【问题描述】:

当 HttpContext 不可用时,我想使用 Castle Windsor 注册 FakeHttpContext。谁能帮我把下面的 Autofac-registration 翻译成 Castle Windsor。

        builder.Register(c => HttpContext.Current != null ? 
            (new HttpContextWrapper(HttpContext.Current) as HttpContextBase) : 
            (new FakeHttpContext("~/") as HttpContextBase))
            .As<HttpContextBase>()
            .InstancePerHttpRequest();

【问题讨论】:

  • 看看AddComponentInstancestackoverflow.com/questions/925244/…
  • 谢谢,但我不明白,如果真正的 HttpContext 不可用,我怎么能只添加 FakeContext。例如服务需要 HttpContext 并且通常它会得到它,但在某些情况下,服务被调用并且没有 HttpContext 可用。只有在这些情况下才应该使用 Fake。

标签: c# castle-windsor autofac httpcontext


【解决方案1】:

您可以通过使用UsingFactoryMethod 指定一个特定服务来使 Windsor 在解析特定服务时使用工厂方法 - 在您的情况下,这样的事情应该可以解决问题:

container.Register(
    Component.For<HttpContextBase>()
        .UsingFactoryMethod(k => HttpContext.Current != null
            ? (HttpContextBase)new HttpContextWrapper(HttpContext.Current)
            : new FakeHttpContext("~/"))
        .Lifestyle.PerWebRequest
);

为了注入当前请求,遵循类似的方法:

container.Register(
    Component.For<HttpRequestBase>()
        .UsingFactoryMethod(k => k.Resolve<HttpContextBase>().Request)
        .Lifestyle.PerWebRequest
);

【讨论】:

  • 我收到以下错误:(无法确定条件表达式的类型,因为'System.Web.HttpContextWrapper'和'Xinga.Core.Fakes.FakeHttpContext'之间没有隐式转换)
  • 我将您的代码更改如下: container.Register( Component.For() .UsingFactoryMethod(k => HttpContext.Current != null ? new HttpContextWrapper(HttpContext.Current) as HttpContextBase : new FakeHttpContext("~/") as HttpContextBase) );但现在我收到以下错误:{“FactoryMethodActivator`1 received misconfigured component model for Late bound System.Web.HttpContextBase. You sure you register this component with 'UsingFactoryMethod'?”}
  • 感谢您指出我需要明确说明工厂方法的返回类型...我相应地更新了代码示例
  • 你遇到了奇怪的错误 - 你能不能给我看看你的温莎代码?
  • 这个错误是由于我的代码中的另一个错误造成的。我修复了这个问题,现在代码可以编译并运行,但它还不能工作。我还必须将以下 Autofac 代码翻译成 Castle Windsor: builder.Register(c => c.Resolve().Request) .As() .InstancePerHttpRequest();你知道如何为 Castle 写这个吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多