Ninject - how to hold constants in a scope?
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 cons开发者_如何学Pythontants 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?
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.
精彩评论