Using Ninject IOC to replace a factory
I've got a factory method inside a parser. Essentially as I load a token I look up the handler for that token, or drop through to the default handler. I've implemented this as a switch
and as a Dictionary<string,Type>
but both approaches require me to store the mapping somewhere else than the handler class.
We are using Ninject for IOC and so I've realized I can also do it using
kernel.Get<ITokenHandler>(tokenName);
but that doesn't save me storing the i开发者_如何学运维nformation on what token the handler can deal with in 2 locations. Is there a way I can decorate the handler so this gets mapped automatically?
If I follow your question correctly, it sounds like you want to retrieve a named binding. You didn't mention what version of Ninject you are using, but based on your code snippet, I am guessing you are using Ninject 2.0. If that's the case then I would think this would suffice for your binding in your module:
Bind<ITokenHandler>().To<YourConcreteTypeHere>().Named(tokenName);
You bind as many concrete types to the same interface and differentiate them by name, and then retrieve them using the precise syntax you've specified in your question.
If I am missing something key, let me know.
One technique I've used is to Bind
stuff in such a way that you can require handing in of a parameter (in the context) at the point where you want someone to select something out.
Between http://ninject.codeplex.com/wikipage?title=Providers%20and%20the%20Activation%20Context and http://ninject.codeplex.com/wikipage?title=Contextual%20Binding you should be able to Bind things in such a way that you can say Only(When.Context...)
to make the selection work?
精彩评论