适用于Castle Windsor的Autofac改装

时间:2011-12-19 02:35:13

标签: c# castle-windsor autofac httpcontext

当HttpContext不可用时,我想使用Castle Windsor注册FakeHttpContext。任何人都可以帮我将以下Autofac注册转换为Castle Windsor。

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

1 个答案:

答案 0 :(得分:3)

您可以通过使用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
);