views:

133

answers:

2

Given the class Ninja, with a specified binding in the Ninject kernel I can resolve an object doing this:

var ninja = ninject.Get<Ninja>();

But why can't I do this:

Type ninjaType = typeof(Ninja); 
var ninja = ninject.Get<ninjaType>();

What's the correct way of specifying the type outside the call to Get?

A: 

Since the purpose of the T is to specify the type you want. Ninject receives your type T and calls typeof(T) on your behalf. I think that this way your code is shorter. Don't you think?

Ikaso
Sounds reasonable. I have a function which needs to receive the type - should it receive it template style then?
stiank81
-1er: Dont know if I would have upvoted this, but I think it's factually correct and not unhelpful. Hence a +1 to do a -1 without a justification in a comment. Scattering -1s like this around just give the poster +8 that might not otherwise have happened.
Ruben Bartelink
+4  A: 

Specifying type arguments is not a runtime thing, it's statically compiled. The type must be known at compile time. In your scenario, it is potentially unknown, or computed at runtime. Through reflection it is possible to construct a method call where you specify the type arguments, but it's unlikely you want to do that.

Also, most containers should have an overload that would look something like this:

Type ninjaType = typeof(Ninja); 
var ninja = (Ninja)ninject.Get(ninjaType);

Finally, most containers should provide ways to specify in the container configuration, which type should be provided on certain conditions. I know that Ninject has a pretty DSL to conditionally specify which type should be returned under what circumstances. This would mean however, to code against an abstraction and let the container decide what is returned:

class DependencyConsumer {
  ctor(IWarrior warrior) {
    //Warrior could be a ninja, because e.g. you told NInject
    //that the dependency should be filled that way for this class
  }
}
flq
Thanks! Good explanation.
stiank81