Is there a clean way to bind to a nested generic "wildcard" in Ninject?
I know that I can ask for any arbitrary IThing<T>
with the following binding:
kernel.Bind(typeof(IThing<>)).To(typeof(Thing<>));
However, what I really want is any arbitrary IThing<Foo<T>>
. The following does not work syntactically:
kernel.Bind(typeof(IThing<Foo<>>)).To(typeof(FooThing<>));
This works syntactically:
kernel.Bind(typeof(IThing<>).MakeGenericType(typeof(Foo<>))).To(typeof(FooThing<>));
But ninject doesn't know what to do with that. Can Ninject achieve this sort of thing?
The simple answer is: no, you cannot do this with Ninject. In fact, the only DI library that actually supports this kind of complex bindings using partially closed generic types is Simple Injector. In Simple Injector you can do this:
container.RegisterOpenGeneric(
typeof(IThing<>),
typeof(Thing<>).MakeGenericType(typeof(Foo<>)));
And in your example you have a FooThing<T>
that probably contains a nested type constraint as follows:
public class FooThing<T> : IThing<Foo<T> { }
Again, Ninject does not support this. I believe that Autofac has some support for this up to some level, but only Simple Injector is able to resolve types for your with almost any bizarre and complex generic type constraints. In Simple Injector that registration is simply:
container.RegisterOpenGeneric(typeof(IThing<>), typeof(FooThing<>));
And Simple Injector will find out for you that it has to resolve a FooThing<int>
when an IThing<Foo<int>>
is requested.