是否可以设置 ninject 绑定(bind)以遵守通用约束?
例如:
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>>();
}
}
按原样调用此代码将产生多激活路径异常:-
Error activating IRepository{Foo}: More than one matching bindings are available.
如何将绑定(bind)设置为以 T 的值为条件?理想情况下,我希望它们从目标类型中获取约束,因为我已经在那里定义了它们,但如果我必须在绑定(bind)中再次定义它们,那也是可以接受的。
最佳答案
也许有更简洁的解决方案,但它绝对适用于 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]));
关于c# - Ninject - 绑定(bind)通用类型与约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12779482/