Search code examples
genericstypesinterfaceninjecttype-constraints

Get all types that inherit generic constraint in Ninject


I have generic type IMyGeneric<T> where T : IBase.

How can I get all types inherit IMyGeneric<T> in ninject?

I tried this:

this.kernel.GetAll<IMyGeneric<IBase>>();

but that is not working and its returning 0 results.

I could get everything that is inheriting IBase and then foreach all types and use this.kernel.Get(type) but then I would have IEnumerable<object> and not IEnumerable<IMyGeneric<IMyInheritedType>> and would not be able to cast and return then as specific type e.g. IEnumerable<IMyGeneric<IBase>> because I get error on cast.


Solution

  • Ninject only supports injecting types which are specifically registered. With two exceptions:

    1. if the requested type is instanciatable (for example when you request FooClass and FooClass contains an accessible constructor).
    2. open generic bindings (you have a closed generic, so it doesn't help here)

    Means if you want to resolve several IMyGeneric<IBase> you will need to register several:

    Bind<Apple>().To<IMyGeneric<IBase>>();
    Bind<Pear>().To<IMyGeneric<IBase>>();
    

    or, if these types need to be resolvable by multiple types:

    Bind(typeof(Apple)).To(typeof(IMyGeneric<IBase>), typeof(IMyGeneric<Apple>));
    

    Instead of manually defining all the bindings you can make use of the Conventions Extension and use a custom IBindingGenerator to create the bindings. Or of course you could also write your own reflection based helper.