How to implement this dependency (HttpContext) in Unity?

we have a class with dependency on HttpContext . We implemented it as follows:

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

Now what I want to do is create an instance of the SiteVariation class through Unity , so we can create one constructor. But I do not know how to configure this new HttpContextWrapper(HttpContext.Current)) in Unity in configuration mode.

ps is the configuration method that we use

 <type type="Web.SaveRequest.ISaveRequestHelper, Common" mapTo="Web.SaveRequest.SaveRequestHelper, Common" /> 
+7
source share
2 answers

I would not directly depend on the HttpContextBase . Instead, I will create a wrapper around it and use the bits you need:

 public interface IHttpContextBaseWrapper { HttpRequestBase Request {get;} HttpResponseBase Response {get;} //and anything else you need } 

then implementation:

 public class HttpContextBaseWrapper : IHttpContextBaseWrapper { public HttpRequestBase Request {get{return HttpContext.Current.Request;}} public HttpResponseBase Response {get{return HttpContext.Current.Response;}} //and anything else you need } 

That way, your class now just relies on the shell and doesn't need the actual HttpContext to work. It makes it much easier to inject, and much easier to check:

 public SiteVariation(IHttpContextBaseWrapper context) { } var container = new UnityContainer(); container.RegisterType<IHttpContextBaseWrapper ,HttpContextBaseWrapper>(); 
+11
source

Microsoft has already built large wrappers and abstractions around the HttpContext , HttpRequest and HttpResponse that are included in .NET, so I will definitely use them directly, rather than wrapping them myself.

You can configure Unity for the HttpContextBase with an InjectionFactory , for example:

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

Also, if you need HttpRequestBase (which I usually use the most) and HttpResponseBase , you can register them as follows:

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

You can easily make fun of HttpContextBase , HttpRequestBase and HttpResponseBase in unit tests without custom wrappers.

+24
source

All Articles