Strategy Design Diagram with IOC Containers - Specifically for Ninject

I have a class that will have to use a strategy development template. At runtime, I have to switch different algorithms to see effects on application performance.

Currently, the class in question takes four parameters in the constructor, each of which is an algorithm.

How to use Ninject (or a generic approach) can I use IOC, but use a strategy template?

The current limitation is that my kernel (container) is aware of each interface of the algorithm, but this can only be associated with one specific class. The only way I can see at the moment is to go through all eight algorithms in the construction, but use different interfaces, but this seems completely incomplete. I would not have done this if I had not used the IOC container, so there should be something like that.

Code example:

class MyModule : NinjectModule { public override void Load() { Bind<Person>().ToSelf(); Bind<IAlgorithm>().To<TestAlgorithm>(); Bind<IAlgorithm>().To<ProductionAlgorithm>(); } } 

A person must use both algorithms so that I can switch at runtime. But only TestAlgorithm is bound, since it is the first in the container.

+6
c # design-patterns strategy-pattern ioc-container ninject
source share
2 answers

Let's take a step back and take a look at a slightly larger shot. Since you want to be able to switch Strategy at runtime, there must be some kind of signaling mechanism that tells Lika to switch Strategy. If you use the UI interface, there may be a button or drop-down list in which the user can choose which strategy to use, but even if it is not, some external caller should display some of the run-time data to the Strategy instance.

The standard DI solution when you need to map a run-time instance to a dependency is to use an abstract Factory .

Instead of registering individual strategies in a container, you are registering a factory.

You can fully write the full API to be DI friendly, but still DI Container-agnostic .

+6
source share

If you need to change the implementation of IAlgorithm at run time, you can change Person to require a factory algorithm that provides various specific algorithms based on the execution conditions.

Some dependency injection containers allow you to associate with anonymous delegate creators - if Ninject supports this, you can put the solution logic in one of them.

+3
source share

All Articles