Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc injecting httpcontext into service layer

I have having a big issue while injecting httpContextBase into my a service level object injected into controller using unity.

sample controller

public HomeController : Controller{
    private IWorkContext _context;

    public HomeController(IWorkContext context){
        _context = context;
    }

}


public WorkContext : IWorkContext{

    private HttpContextBase _httpContext;

        public (HttpContextBase httpContext){
            _httpContext = httpContext;
        }

        public void DealWithCookies(){
            //do some thing with http context and deal with cookies
        }
    }

Inside unity bootstrapper

container.RegisterType<HttpContextBase>().RegisterInstance(new HttpContextWrapper(HttpContext.Current) as HttpContextBase, new ContainerControlledLifetimeManager());

//With this line httpcontextbase is returned but as a singleton instead of new for each request.


   container.RegisterType<HttpContextBase>().RegisterInstance(new HttpContextWrapper(HttpContext.Current) as HttpContextBase, new PerRequestLifetimeManager());

//This line returns an exception 

The type HttpContextBase does not have an accessible constructor.

like image 986
Mudasar Rauf Avatar asked Oct 21 '22 19:10

Mudasar Rauf


1 Answers

I wouldn't inject the HttpContext at all - I would pass it into each method call:

public WorkContext : IWorkContext{

    private HttpContextBase _httpContext;

    public WorkContext(){
        ...
    }

    public void DealWithCookies(HttpContext ctx){
        //do some thing with http context and deal with cookies
    }
}

Trying to use dependency injection here seems to be a misappropriation of the principle to me. Dependency injection allows you to loosely-couple your components but there's no need for this here since you can pass the context into methods and manipulate it directly. There's no interface to provide a concrete implementation of so there's no benefit to DI - it's just unnecessary bootstrapping and an "anti-pattern" lack of structure.

Not to mention that you're not going to be able to do this anyway given that when you register your types on application launch, there's no instance to register (and the instance needs to change on each request).

On a side note - I hope that IWorkContext is solely for abstracting cookie logic and isn't a layer between your application and your data layer. If not, it shouldn't have a dependency on an HTTP context at all.

like image 112
Ant P Avatar answered Oct 24 '22 00:10

Ant P