Acessing HttpContext from request-scoped class
-
27-10-2019 - |
Question
I have a class, inherited from IDependency. What is the best way to access HttpContext from my class? I want to access it as early a possible, once HttpContext becomes available.
I tried to add dependency injection for IWorkContextAccessor to my class, and access it from the constructor, but GetContext() returns null then.
Solution
Current HttpContext is available via IWorkContextAccessor object after the IoC container objects get created, so you won't be able to access those in the constructor. The best way is to access the context object when you want to use it - not earlier - especially not inside the constructor, as constructors get called very early by the Autofac.
You can also inject IOrchardServices object (let's call it "services") and then use the services.WorkContext.HttpContext object.
Could you provide some greater detail at what you want to achieve? Why would you want to access that so early? Couldn't this be rewritten so the context object will be used later (eg. in some method call)?
HTH