我正在使用Ninject和ASP.NET MVC 3构建应用程序。 是否可以使用Ninject在这样的模块中提供通用绑定:
Bind(typeof(IRepository<>)).To(typeof(SomeConcreteRepository<>));
修改 然后对于特定类型,创建一个继承自SomeConcreteRepository的类:
Bind(typeof(IRepository<Person>)).To(typeof(PersonConcreteRepository));
这会抛出多个绑定可用的异常。但是,还有另一种方法吗? .NET还有其他支持这种行为的DI框架吗?
答案 0 :(得分:3)
您不需要第二行。只需注册开放的泛型类型:
kernel.Bind(typeof(IRepository<>)).To(typeof(SomeConcreteRepository<>));
以后再获取这样的特定存储库:
var repo = kernel.Get<IRepository<Person>>();
或者你也可以use a provider。
答案 1 :(得分:1)
有点令人讨厌的修复,但对于手头的情况,它有效:
public class MyKernel: StandardKernel
{
public MyKernel(params INinjectModule[] modules) : base(modules) { }
public MyKernel(INinjectSettings settings, params INinjectModule[] modules) : base(settings, modules) { }
public override IEnumerable<IBinding> GetBindings(Type service)
{
var bindings = base.GetBindings(service);
if (bindings.Count() > 1)
{
bindings = bindings.Where(c => !c.Service.IsGenericTypeDefinition);
}
return bindings;
}
}
答案 2 :(得分:0)
public class ExtendedNinjectKernal : StandardKernel
{
public ExtendedNinjectKernal(params INinjectModule[] modules) : base(modules) { }
public ExtendedNinjectKernal(INinjectSettings settings, params INinjectModule[] modules) : base(settings, modules) { }
public override IEnumerable<IBinding> GetBindings(Type service)
{
var bindings = base.GetBindings(service);
//If there are multiple bindings, select the one where the service does not have generic parameters
if (bindings.Count() > 1 && bindings.Any(a => !a.Service.IsGenericTypeDefinition))
bindings = bindings.Where(c => !c.Service.IsGenericTypeDefinition);
return bindings;
}
}