How to implement this (HttpContext) dependency in Unity?

Michel picture Michel · Nov 1, 2011 · Viewed 7.7k times · Source

we have a class with a dependency to the HttpContext. We've implemented it like this:

public SiteVariation() : this(new HttpContextWrapper(HttpContext.Current))
{
}
public SiteVariation(HttpContextBase context)
{}

Now what i want to do is to instantiate the SiteVariation class via Unity, so we can create one constructor. But i do not know how to configure this new HttpContextWrapper(HttpContext.Current)) in Unity in the config way.

ps this is the config way we use

<type type="Web.SaveRequest.ISaveRequestHelper, Common" mapTo="Web.SaveRequest.SaveRequestHelper, Common" />

Answer

Christian Fredh picture Christian Fredh · Mar 22, 2014

Microsoft has already built great wrappers and abstractions around HttpContext, HttpRequest and HttpResponse that is included in .NET so I would definitely use those directly rather than wrapping it myself.

You can configure Unity for HttpContextBase by using InjectionFactory, like this:

var container = new UnityContainer(); 

container.RegisterType<HttpContextBase>(new InjectionFactory(_ => 
    new HttpContextWrapper(HttpContext.Current)));

Additionally, if you need HttpRequestBase (which I tend to use the most) and HttpResponseBase, you can register them like this:

container.RegisterType<HttpRequestBase>(new InjectionFactory(_ => 
    new HttpRequestWrapper(HttpContext.Current.Request)));

container.RegisterType<HttpResponseBase>(new InjectionFactory(_ => 
    new HttpResponseWrapper(HttpContext.Current.Response)));

You can easily mock HttpContextBase, HttpRequestBase and HttpResponseBase in unit tests without custom wrappers.