Using Ninject IOC to replace a factory

c#, factory-pattern, inversion-of-control, ninject

Solution

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.

Problem

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 information 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?

Original source