0

When using dependency injection we declare all dependencies within the constructor. But in ASP.NET MVC Controllers, I rarely see HttpContext injected via constructor. Most probably this is due the fact it's conveniently available via static access in every Controller.

Now I thought it may be a good idea to also declare in the constructor of the HomeController that we need HttpContext (via IHttpContextAccessor) to use this controller. Like this:

public class HomeController : Controller
{
     protected new HttpContext HttpContext { get; }

     public HomeController(IHttpContextAccessor httpContextAccessor)
     {
          HttpContext = httpContextAccessor.HttpContext;
     }
}

Is this a common practice? Does it create major overhead? Or is it even a bad idea?

Sandro
  • 2,998
  • 2
  • 25
  • 51
  • But HttpContext is already available in controllers in asp.net core. – Evk Nov 03 '17 at 16:31
  • Yes, via static access. But that's difficult to test. – Sandro Nov 03 '17 at 16:49
  • `HttpContext` in classes derived from `Controller` is a property, not a type, so it's **not** static access. This was removed in ASP.NET Core. In POCO Controllers you inject it via accessor – Tseng Nov 03 '17 at 21:41
  • There is **no** static access for `HttpContext` in ASP.NET Core. There is no `HttpContext.Current`. You can **only** access the HTTP context by injecting the `IHttpContextAccessor`. The alternative is to inherit from the base controller type which will also already give you the current HTTP context as a property – poke Nov 04 '17 at 00:28
  • 1
    In general, I would say "no", [application components should not be constructed using runtime data](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=99). `HttpContext` _is_ runtime data. – Steven Nov 04 '17 at 09:58
  • @poke sorry my code was not up to date: I **do** inherit from `Controller` which gives me access to the HttpContext without `IHttpContextAccessor` – Sandro Nov 06 '17 at 09:11
  • @Steven I inject `IHttpContextAccessor`, so this would be the adapter for the runtime data. – Sandro Nov 06 '17 at 09:30
  • 1
    No, `IHttpContextAccessor` is the abstraction around runtime data, but it is a rather bad one, since 1. It is very generic in nature and 2. is not defined by your application but by the framework. The `HttpSessionUserContext` example in [this](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=99) article is an example of an adapter on top of an application-tailored abstraction called `IUserContext`. Such adapter could however use `IHttpContextAccessor` internally. – Steven Nov 06 '17 at 09:33
  • Makes sense. Thank you! – Sandro Nov 06 '17 at 10:22

0 Answers0