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?
It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software's architecture, your code will become easier to write, reuse, test and modify.
Step 1: We are creating an instance of Class StandardKernel. Step 2: Then we will load the Kernel. Step 3: Get the instance of the specific service that we want to inject. Step 4: Then inject the dependency.
The Ninject modules are the tools used to register the various types with the IoC container. The advantage is that these modules are then kept in their own classes. This allows you to put different tiers/services in their own modules.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With