I have a class which is going to need to use the strategy design pattern. At run time I am required to switch different algorithms in and out to see the effects on the performance of the application.
The class in question currently takes four parameters in the constructor, each representing an algorithm.
How using Ninject (or a generalised approach) could I still use IOC but use the strategy pattern?
The current limitation is that my kernel (container) is aware of each algorithm interface, but that can only be bound to one concrete class. The only way around this I can see at the moment is pass in all eight algorithms at construction, but use different interfaces, but this seems totally uncessary. I wouldn't do this if I was not using an IOC container, so there must be some way around this.
Code example:
class MyModule : NinjectModule
{
public override void Load()
{
Bind<Person>().ToSelf();
Bind<IAlgorithm>().To<TestAlgorithm>();
Bind<IAlgorithm>().To<ProductionAlgorithm>();
}
}
Person needs to make use of both algorithms so I can switch at run time. But only TestAlgorithm is bound, as it's the first one in the container.
NInject is a popular IOC container that can be used to inject dependencies in your WebAPI controllers easily. IDG. Dependency injection is a software design pattern that helps you to build pluggable implementations in your application using loosely coupled, testable components.
IoC Container (a.k.a. DI Container) is a framework for implementing automatic dependency injection. It manages object creation and it's life-time, and also injects dependencies to the class.
Let's take a step back and examine a slightly bigger picture. Since you want to be able to switch Strategy at run-time, there must be some kind of signalling mechanism that tells Person to switch the Strategy. If you application is UI-driven, perhaps there a button or drop-down list where the user can select which Strategy to use, but even if this is not the case, some outside caller must map a piece of run-time data to an instance of the Strategy.
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 the individual Strategies with the container, you register the factory.
It is entirely possible to write a complete API so that it's DI-friendly, but still DI Container-agnostic.
If you need to vary the IAlgorithm
implementation at run-time, you can change Person
to require an algorithm factory that provides different concrete algorithms based on run-time conditions.
Some dependency injection containers let you bind to anonymous creational delegates - if Ninject supports that, you could put the decision logic in one of those.
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