开发者

Specifying type when resolving objects through Ninject

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 t开发者_Go百科he call to Get?


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
  }
}


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜