Ninject - how to hold constants in a region?

I want to send messages from different parts of the application (ASP.NET) to several listeners (for example: controls that display these messages => listener lifetime = request timeout). Listeners are of different types so that they can be filtered when messages are received. I want to implement this functionality using Ninject in order to become more flexible (adding various areas, types of solutions, ...). At the moment, I only need the case of the request area, and I developed without Ninject using HttpContext.Current.Item["MyCollectionOfListeners"] , but this is too specific and I want to provide more flexibility.

So far, I have not been able to find a solution for storing constants in scope and reusing these constants only for this scope. For example, a constant can be an ASP.NET control whose lifetime begins inside its constructor and ends with the PreRender event (because it is of little use on Render ). This means that this listener instance will be added to Ninject and then deleted on PreRender .

I was thinking of something like:

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

or

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

but that does not fit my case. Also, a constant is returned for each request, and the binding does not disappear from the collection after the constant goes beyond the bounds. Also, I do not know how to remove a binding based on a given listener (constant).

What is the correct way to solve such a scenario with Ninject?

+4
source share
1 answer

The constants are constant, which means that they are in single units and are defined once during the determination of the binding. They should not be used in other areas.

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

+2
source

Source: https://habr.com/ru/post/1342434/


All Articles