2011-05-09 87 views
0

我建立使用Ninject和ASP.NET MVC应用程序3. 是否有可能与Ninject到这样一个模块内提供一个通用的绑定:Ninject通用绑定

Bind(typeof(IRepository<>)).To(typeof(SomeConcreteRepository<>)); 

编辑: 和那么对于特定类型,创建一个继承自SomeConcreteRepository的类:

Bind(typeof(IRepository<Person>)).To(typeof(PersonConcreteRepository)); 

这引发了一个例外情况,即多个绑定可用。但是,有没有另一种方法呢?有没有其他支持这种行为的.NET的DI框架?

回答

1

手头讨厌的修复方案,但对于A位它的工作原理:

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; 
    } 
    } 
+0

我使用了相同的方法,但我精炼了if语句以验证是否存在一个非通用服务绑定 – 2012-05-14 15:50:41

3

你不需要第二行。只需注册开放式泛型类型:

kernel.Bind(typeof(IRepository<>)).To(typeof(SomeConcreteRepository<>)); 

后来获取特定的资源库是这样的:

var repo = kernel.Get<IRepository<Person>>(); 

,或者您也可以use a provider

+0

我觉得我的问题不是很清楚了:)参阅编辑 – sTodorov 2011-05-09 06:36:40

+0

@sTodorov,你看到的提供商链接我张贴在我的答案? – 2011-05-09 06:45:18

+0

是的,我非常感谢你。我目前正在考虑扩展提供者,或者创建一个定制的内核并重写一些方法。会告诉你这件事的进展的。 – sTodorov 2011-05-09 06:54:49

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; 
    } 
}