Search code examples
c#genericsdependency-injectionninject

Ninject bind open generic interface with open generic implementation having the same closing types


I have been reading other questions and answers but I can't quite figure out the answer to my solution.

I have the following scenario:

class BaseA {}

class BaseB {}

IInterface<TClassA, TClassB> 
    where TClassA : BaseA
    where TClassB : BaseB

IterfaceImplementation<TClassA, TClassB> :IInterface<TClassA, TClassB> 
    where TClassA : BaseA
    where TClassB : BaseB

class A : BaseA {}

class B : BaseB {}

Note: BaseA and BaseB do not implement interfaces.

With this setup what I need to do in order for Ninject to bind

 IIntreface<A,B>

to

 InterfaceImplementation<A,B>

I have to have a binding

 kernel.Bind<IInterface<A,B>>().To<InterfaceImplementation<A,B>>()

However, I am trying to avoid this because of multiple implementations of BaseA and BaseB and do not want to have to do additional bindings for each implementation. What I want to do is

Bind<IInterface<Any(BaseA), Any(BaseB>>().To<InterfaceImplementation<ThatSame(A), ThatSame(B)>>();

Is there any way to this?


Solution

  • Specifying open generics always works the same way in .NET:

    kernel.Bind(typeof(IInterface<,>)).To(typeof(InterfaceImplementation<,>));
    

    Which will bind it so any interface closing types will be used for the implementation. The comma can be used as a separator to specify the number of open generic parameters.