views:

61

answers:

1

Hi guys,

I am new to ninject, I am wondering how I can run custom initizlisation code when constructing the injected objects? ie. I have a Sword class which implements IWeapon, but I want to pass an hit point value to the Sword class constructor, how do I achieve that? Do I need to write my own provider?

A minor question, IKernel kernel = new StandardKernel(new Module1(), new Module2(), ...); what is the actual use of having multiple modules in Kernel? I sorta understand it, but could someone give me a formal explaination and use case?

Thanks a lot!

James

+1  A: 

If you have a class Sword with this constructor:

public Sword(int hitPoints)
    ...

Rather than implementing a Provider, you may prefer to instantiate Swords like this:

IWeapon sword1 = kernel.Get<IWeapon>(With.Parameters.ConstructorArgument("hitPoints", 10));
IWeapon sword2 = kernel.Get<IWeapon>(With.Parameters.ConstructorArgument("hitPoints", 20));
anthony
Good answer, now what if I have a Warrior class uses that Sword class(by IWeapon), eg Warrior james = kernel.Get<Warrior>(); How do I pass in the hit point value into the Sword object?
James Lin
if I have to run this command IWeapon sword1 = kernel.Get<IWeapon>(With.Parameters.ConstructorArgument("hitPoints", 10)); to get the sword object, why can't I just run IWeapon sowrd1 = new Sword(10); ???
James Lin
Good questions. To answer your first question, if you need that level of control then you should instantiate Sword instances using a presenter.As for your second question, the power of dependency injection is that you can decouple your design from it's implementation. If you always want a Sword, and you know that you always _will_ want a sword, then you probably don't need DI.
anthony
oops, when i said "presenter" above, i meant a ninject provider. see: http://wiki.github.com/ninject/ninject/providers-factory-methods-and-the-activation-context
anthony