简体   繁体   English

如何在Ninject中绑定Generic类型的接口

[英]How to bind Generic-type interfaces in Ninject

I'm fairly new to Ninject, and found myself stumbling when I came to implement a generic repository pattern. 我是Ninject的新手,在我实现通用存储库模式时发现自己陷入困境。 I want to bind a dependency IRepository<IEntityType> to a class ConcreteRepository<EntityType> where ConcreteRepository<T> implements IRepository<T> and EntityType implements IEntityType. 我想将依赖关系IRepository <IEntityType>绑定到类ConcreteRepository <EntityType> ,其中ConcreteRepository <T>实现IRepository <T>,EntityType实现IEntityType。 I tried this: 我试过这个:

kernel.Bind<IRepository<IEntityType>>().To<ConcreteRepository<EntityType>>();

...but Ninject won't take that because it doesn't know or care that EntityType implements IEntityType. ...但是Ninject不会接受它,因为它不知道或不关心EntityType实现IEntityType。 How can I go about binding this dependency? 我怎样才能绑定这种依赖?

UPDATE UPDATE

This is the error I'm getting: 这是我得到的错误:

Error 3 The type 'ICM.Dependency.Repository.ConcreteRepository' cannot be used as type parameter 'TImplementation' in the generic type or method 'Ninject.Syntax.IBindingToSyntax.To()'. 错误3类型'ICM.Dependency.Repository.ConcreteRepository'不能在泛型类型或方法'Ninject.Syntax.IBindingToSyntax.To()'中用作类型参数'TImplementation'。 There is no implicit reference conversion from 'ConcreteRepository<EntityType>' to 'IRepository<IEntityType>'. 没有从“ConcreteRepository <EntityType>”到“IRepository <IEntityType>”的隐式引用转换。

SOLUTION

I still don't quite understand why my binding doesn't work, but evidently I was using generics incorrectly there. 我仍然不太明白为什么我的绑定不起作用,但显然我在那里错误地使用泛型。 As such the solution doesn't really relate to NInject. 因此,该解决方案与NInject无关。 I ended specifying the ConcreteRepository to explicitly connect IEntityType with TEntityType: 我结束了指定ConcreteRepository以显式连接IEntityType和TEntityType:

public class ConcreteRepository<TInterface, TEntity> : IRepository<TInterface> where TEntity : TInterface { ... }

Then the injection can be written as follows: 然后注射可写如下:

kernel.Bind<IRepository<IEntityType>>().To<ConcreteRepository<IEntityType,EntityType>>()
kernel.Bind(typeof(IRepository<>)).To(typeof(SimpleRepository<>));

Take a look at my one if you want here: http://blog.staticvoid.co.nz/2011/10/staticvoid-repository-pattern-nuget.html i have binding examples 如果你想在这里看看我的那个: http//blog.staticvoid.co.nz/2011/10/staticvoid-repository-pattern-nuget.html我有绑定的例子

EDIT: 编辑:

The error you are getting is saying that your concrete repository isnt an instance of the generic one you want to bind to, ie you will need to do this 您得到的错误是说您的具体存储库不是您要绑定到的通用存储库的实例,即您需要执行此操作

public class ConcreteRepository<ConcreteEntity> : IRepository<IEntity>{}

not

public class ConcreteRepository<ConcreteEntity> : IRepository<ConcreteEntity>{}

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

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