c# – Ninject – 绑定带约束的泛型类型
发布时间:2020-12-15 21:41:01 所属栏目:百科 来源:网络整理
导读:是否可以设置ninject绑定以遵守通用约束? 例如: interface IFoo { }interface IBar { }interface IRepositoryT { }class FooRepositoryT : IRepositoryT where T : IFoo { }class BarRepositoryT : IRepositoryT where T : IBar { }class Foo : IFoo { }cl
是否可以设置ninject绑定以遵守通用约束?
例如: 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>>(); } } 按原样调用此代码将产生多个激活路径异常: –
如何设置绑定以T的值为条件?理想情况下,我希望他们从目标类型中获取约束,因为我已经在那里定义了它们,但是如果我必须在绑定中再次定义它们也是可以接受的. 解决方法
也许有一个更清洁的解决方案,但它绝对适用于When
contextual binding方法和一些反思:
// 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])); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |