I’m re-working on the design of an existing application which is build using WebForms. Currently the plan is to work it into a MVP pattern application while using Ninject as the IoC container.
The reason for Ninject to be there is that the boss had wanted a certain flexibility within the system so that we can build in different flavor of business logic in the model and let the programmer to choose which to use based on the client request, either via XML configuration or database setting.
I know that Ninject have no need for XML configuration, however I’m confused on how it can help to dynamically inject the dependency into the system?
Imagine I have a interface IMember
and I need to bind this interface to the class decided by a xml or database configuration at the launch of the application, how can I achieve that?
This is pretty much explained in the Ninject-wiki It has this example of doing individual bindings based on some condition:
class WeaponsModule : NinjectModule
{
private readonly bool useMeleeWeapons;
public WeaponsModule(bool useMeleeWeapons) {
this.useMeleeWeapons = useMeleeWeapons;
}
public void Load()
{
if (this.useMeleeWeapons)
Bind<IWeapon>().To<Sword>();
else
Bind<IWeapon>().To<Shuriken>();
}
}
class Program
{
public static void Main()
{
bool useMeleeWeapons = false;
IKernel kernel = new StandardKernel(new WeaponsModule(useMeleeWeapons));
Samurai warrior = kernel.Get<Samurai>();
warrior.Attack("the evildoers");
}
}
If you don’t need this much granularity, you could have different Modules that are loaded based on some condition.
3