Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement this (HttpContext) dependency in Unity?

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" />
like image 848
Michel Avatar asked Nov 01 '11 14:11

Michel


1 Answers

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.

like image 186
Christian Fredh Avatar answered Sep 23 '22 17:09

Christian Fredh