简体   繁体   中英

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 the 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM