Ninject - constrained generic type binding

Is it possible to set a ninject binding to comply with a general constraint?

For instance:

interface IFoo { } interface IBar { } interface IRepository<T> { } class FooRepository<T> : IRepository<T> where T : IFoo { } class BarRepository<T> : IRepository<T> where T : IBar { } class Foo : IFoo { } class Bar : IBar { } class Program { static void Main(string[] args) { IKernel kernel = new StandardKernel(); // Use this binding only where T : IFoo kernel.Bind(typeof(IRepository<>)).To(typeof(FooRepository<>)); // Use this one only where T : IBar kernel.Bind(typeof(IRepository<>)).To(typeof(BarRepository<>)); var fooRepository = kernel.Get<IRepository<Foo>>(); var barRepository = kernel.Get<IRepository<Bar>>(); } } 

Calling this as-is code will exclude several activation paths: -

IRepository activation error {Foo}: several matching bindings are available.

How to configure bindings for conditional value T? Ideally, I would like them to select constraints from the target type, since I already defined them there, but if I have to define them again in a binding, which is also acceptable.

+4
source share
1 answer

There may be a cleaner solution, but it definitely works with the When method of context binding and some reflection:

 // Use this binding only where T : IFoo kernel.Bind(typeof(IRepository<>)).To(typeof(FooRepository<>)) .When(r => typeof(IFoo).IsAssignableFrom(r.Service.GetGenericArguments()[0])); // Use this one only where T : IBar kernel.Bind(typeof(IRepository<>)).To(typeof(BarRepository<>)) .When(r => typeof(IBar).IsAssignableFrom(r.Service.GetGenericArguments()[0])); 
+1
source

Source: https://habr.com/ru/post/1438378/


All Articles