1

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?

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
ipohfly
  • 271
  • 1
  • 3
  • 8

1 Answers1

1

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.

simoraman
  • 2,318
  • 17
  • 17
  • yah i read this too, the thing is with this method, i'll need to change the Load() method whenever i add a new weapon type, say Dagger. What i'm looking for is a way where i can just create the implementation class Dagger and at some place add that into a list of weapons for it to work, without changing the code. – ipohfly Oct 15 '12 at 09:30
  • Is it really a problem? Introducing the Dagger-class would be code change anyway? You could also use some other IOC container, one that actually is configurable by XML – simoraman Oct 15 '12 at 09:45
  • Ninject also supports the notion of convention-based bindings. [Stack Overflow](http://stackoverflow.com/questions/4856467/ninject-convention-based-binding) has a question that talks about it. – neontapir Oct 15 '12 at 21:26