从请求范围的类中启用HttpContext。

时间:2022-09-17 11:07:24

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.

我有一个阶级,继承了理想。从我的类访问HttpContext的最佳方式是什么?一旦HttpContext可用,我希望尽早访问它。

I tried to add dependency injection for IWorkContextAccessor to my class, and access it from the constructor, but GetContext() returns null then.

我尝试将IWorkContextAccessor的依赖项注入添加到类中,并从构造函数访问它,但是GetContext()返回null。

1 个解决方案

#1


1  

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.

当前的HttpContext通过IWorkContextAccessor对象提供,在IoC容器对象被创建之后,因此您将无法访问构造函数中的这些对象。最好的方法是在您想要使用上下文对象时访问它——而不是更早——特别是在构造函数内部,因为构造函数很早就被Autofac调用。

You can also inject IOrchardServices object (let's call it "services") and then use the services.WorkContext.HttpContext object.

您还可以注入IOrchardServices对象(我们称之为“服务”),然后使用服务。HttpContext对象。

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

HTH

#1


1  

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.

当前的HttpContext通过IWorkContextAccessor对象提供,在IoC容器对象被创建之后,因此您将无法访问构造函数中的这些对象。最好的方法是在您想要使用上下文对象时访问它——而不是更早——特别是在构造函数内部,因为构造函数很早就被Autofac调用。

You can also inject IOrchardServices object (let's call it "services") and then use the services.WorkContext.HttpContext object.

您还可以注入IOrchardServices对象(我们称之为“服务”),然后使用服务。HttpContext对象。

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

HTH