在Ninject 2中注入HttpContext

编程入门 行业动态 更新时间:2024-10-26 23:36:30
本文介绍了在Ninject 2中注入HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的asp mvc应用程序中,我使用Ninject作为DI框架.

In my asp 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

本文发布于:2023-11-16 09:46:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603166.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Ninject   HttpContext

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!