How to implement this (HttpContext) dependency in Unity?
I wouldn't take a dependency on HttpContextBase
directly. I would instead 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 the 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
}
This way, your class now just relies on a wrapper, and doesn't need the actual HttpContext to function. Makes it much easier to inject, and much easier to test:
public SiteVariation(IHttpContextBaseWrapper context)
{
}
var container = new UnityContainer();
container.RegisterType<IHttpContextBaseWrapper ,HttpContextBaseWrapper>();
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.