Ninject - 如何在范围内保存常量?

发布于 2024-10-20 14:35:54 字数 832 浏览 1 评论 0原文

我想将消息从应用程序 (ASP.NET) 的不同部分发送到多个侦听器(例如:显示这些消息的控件 => 侦听器生命周期 = 请求生命周期)。监听器有不同的类型,以便在接收消息时可以对其进行过滤。 我想使用 Ninject 来实现此功能,以变得更加灵活(添加各种范围、解决类型……)。目前我只需要请求范围的情况,并且我使用 HttpContext.Current.Item["MyCollectionOfListeners"] 在没有 Ninject 的情况下进行开发,但这太特殊了,我想提供更大的灵活性。

到目前为止,我还没有找到一种解决方案来将常量保存在某个范围内并仅在该范围内重用该常量。 例如,常量可能是一个 ASP.NET 控件,其生命周期在其构造函数内开始,并在 PreRender 事件中结束(因为 on Render 没有什么用处)。 这意味着该侦听器实例将添加到 Ninject,然后在 PreRender 上删除。

我想做一些类似的事情:

Kernel.Bind<IMessageListener>.ToConstant(listener).InRequestScope();

或者

Kernel.Bind<IMessageListener>.ToConstant(listener).InScope(ctx => listener);

但这不适合我的情况。此外,每个请求都会返回常量,并且在常量超出范围后绑定不会从集合中消失。 另外,我不知道如何删除基于给定侦听器(常量)的绑定。

使用 Ninject 解决这种情况的正确方法是什么?

I want to send messages from different parts of the application (ASP.NET) to multiple listeners (eg: controls displaying those messages => listener lifetime = request lifetime). Listeners have different types so that they can be filtered when receiving messages.
I want to implement this functionality using Ninject to become more flexible (adding various scopes, solving types, ...). For now I needed only the request scope case and I developed without Ninject by using HttpContext.Current.Item["MyCollectionOfListeners"] but this is too particular and I want to provide more flexibility.

So far I haven't managed to find a solution to hold constants in a scope and to reuse this constants only for that scope.
For example a constant may be a ASP.NET control which lifetime begins inside its constructor and ends in PreRender event (because on Render is of little use).
This imply that this listener instance be added to Ninject and then removed on PreRender.

I thought of doing something like:

Kernel.Bind<IMessageListener>.ToConstant(listener).InRequestScope();

or

Kernel.Bind<IMessageListener>.ToConstant(listener).InScope(ctx => listener);

but this doesn't serve my case. Also the constant is returned for every request and the binding doesn't disappear from collection after the constant is out of scope.
Also I don't know how to remove a binding based on a given listener (constant).

What is the proper way to solve such a scenario using Ninject?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

反话 2024-10-27 14:35:54

常量是常量,这意味着它们是单例,并且在定义绑定时定义一次。它们不应该在其他范围内使用。

您想要做的是通过使用 ToMethodToProvider 返回实例来完成。该范围很可能在请求范围内,或者可能是控件所在的页面。第二个选项有点复杂。

Constants are constant, which implies that they are in singletons and defined once at the time the binding is defined. They shouldn't be used in another scope.

What you want to do is done by using ToMethod or ToProvider to return the instance. The scope is most likely in request scope or may be the page the control is placed on. The second option is a bit more complicated.

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