在 Ninject 2 中注入 HttpContext
在我的 asp.net mvc 应用程序中,我使用 Ninject 作为 DI 框架。
我的控制器使用我的 HttpAccountService 从 cookie 获取信息或向 cookie 获取信息。 为此,我需要 HttpAccountService 中的 HttpContext.Current。 由于这是一个依赖项,我通过构造函数注入它:
kernel.Bind<IAccountService>()
.To<HttpAccountService>()
.InRequestScope()
.WithConstructorArgument("context", HttpContext.Current);
遗憾的是,这总是绑定到相同的上下文,这使得在第一个请求完成后该上下文变得过时。
我应该如何正确注入我的 HttpContext?
In my asp.net mvc application I'm using Ninject as a DI framework.
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.
How should I correctly inject my HttpContext?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
WithConstructorArgument
有一个重载,它需要一个Func
,即,您可以使用:将调用请求处理中提供的“回调”lambda 并在该时间点获取正确的值[而不是调用其他重载并提供在 Bind<> 时间计算的常量值]。
(如果您不想模拟上下文,我假设您会考虑内联使用它)
WithConstructorArgument
has an overload that takes aFunc<NinjectContext,T>
, i.e., you can use: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)