andre
andre

Reputation: 140

Autofac adaptation for Castle Windsor

I want to use Castle Windsor to register a FakeHttpContext when the HttpContext is not available. Can anybody help me to translate the following Autofac-registration into Castle Windsor.

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

Upvotes: 0

Views: 1187

Answers (1)

mookid8000
mookid8000

Reputation: 18628

You can make Windsor use a factory method when resolving a particular service by specifying one with UsingFactoryMethod - in your case, something like this should do the trick:

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

In order to inject the current request, follow a similar approach:

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

Upvotes: 3

Related Questions