views:

471

answers:

2

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?

+1  A: 

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?

Ruben Bartelink
Only just saw the other answer (as was +1'd on this). The other answer looks like a much more explicitly and clear approach so I'd definitely prefer it if possible - my approach is a more general approach for when built in ways arent possible.
Ruben Bartelink
+4  A: 

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.

Peter Meyer
A bit late to getting back here. What I was really after was a way to mark up the ITokenHandler concrete classes so that I could define the bindings where the Handler was declared. I've now gone with your example are all bar 1 of the bindings is of the pattern: Bind<ITokenHandler>().To<GenericTokenHandler<TokenTypeToConstruct>>().Named(tokenName);
baralong