在Ninject 2中注入HttpContext [英] Injecting HttpContext in Ninject 2
问题描述
在我的asp.net mvc应用程序中,我使用Ninject作为DI框架.
In my asp.net mvc application I'm using Ninject as a DI framework.
我的控制器使用我的HttpAccountService从cookie中获取信息. 为此,我需要HttpAccountService中的HttpContext.Current. 因为这是一个依赖关系,所以我将它通过构造函数注入了它:
My HttpAccountService is used by my controllers to get info from and to cookies. For this I need the HttpContext.Current in the HttpAccountService. As this is a dependency I injected it throught the constructor as such:
kernel.Bind<IAccountService>()
.To<HttpAccountService>()
.InRequestScope()
.WithConstructorArgument("context", HttpContext.Current);
可悲的是,它始终绑定到相同的上下文,这使得在第一个请求完成之后,该上下文变得过时了.
Sadly this always binds to the same context which makes that after the first request finishes this context becomes outdated.
我应该如何正确注入HttpContext?
How should I correctly inject my HttpContext?
推荐答案
WithConstructorArgument
具有需要Func<NinjectContext,T>
的重载,即,您可以使用:
WithConstructorArgument
has an overload that takes a Func<NinjectContext,T>
, i.e., you can use:
...
.WithConstructorArgument("context",
ninjectContext =>HttpContext.Current);
它将在请求处理中调用提供的回调" lambda,并在该时间点获得正确的值(与您调用另一个重载并提供在Bind<>
时计算得出的常数值相反).
which will call the provided 'callback' lambda within the request processing and obtain the correct value at that point in time [as opposed to you calling the other overload and supplying a constant value which gets computed at Bind<>
time].
(如果您不打算模拟上下文,我认为您会考虑内联使用它)
(If you're not trying to Mock the context, I assume you'll consider using it inline)
这篇关于在Ninject 2中注入HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!