简体   繁体   English

Ninject - 绑定具有约束的泛型类型

[英]Ninject - binding generic types with constraints

Is it possible to set up a ninject binding to respect a generic constraint? 是否可以设置ninject绑定以遵守通用约束?

For example: 例如:

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 code as-is will produce a multiple activation paths exception:- 按原样调用此代码将产生多个激活路径异常: -

Error activating IRepository{Foo}: More than one matching bindings are available. 激活IRepository {Foo}时出错:可以使用多个匹配的绑定。

How can I set up the bindings to be conditional on the value of T? 如何设置绑定以T的值为条件? Ideally I'd like them to pick up the constraints from the target type, as I've already defined them there, but if I have to define them again in the binding that's also acceptable. 理想情况下,我希望他们从目标类型中获取约束,因为我已经在那里定义了它们,但是如果我必须在绑定中再次定义它们也是可以接受的。

Maybe there is a cleaner solution but it definitely works with the When contextual binding method and some reflection: 也许有一个更清晰的解决方案,但它绝对适用于When 上下文绑定方法和一些反射:

// 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]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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