Search code examples
c#asp.netinversion-of-controlunity-containerhttpcontext

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" />

Solution

  • 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>();