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" />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With