在 Ninject 2 中注入 HttpContext

发布于 2024-09-17 09:24:35 字数 452 浏览 5 评论 0原文

在我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

牵你手 2024-09-24 09:24:44

WithConstructorArgument 有一个重载,它需要一个 Func,即,您可以使用:

... .WithConstructorArgument("context",ninjectContext=>HttpContext.Current);

将调用请求处理中提供的“回调”lambda 并在该时间点获取正确的值[而不是调用其他重载并提供在 Bind<> 时间计算的常量值]。

(如果您不想模拟上下文,我假设您会考虑内联使用它)

WithConstructorArgument has an overload that takes a Func<NinjectContext,T>, i.e., you can use:

... .WithConstructorArgument("context",ninjectContext=>HttpContext.Current);

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文