如何在 Ninject 中绑定泛型接口 [英] How to bind Generic-type interfaces in Ninject

查看:24
本文介绍了如何在 Ninject 中绑定泛型接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Ninject 还很陌生,当我开始实现一个通用的存储库模式时,我发现自己跌跌撞撞.我想将依赖项 IRepository 绑定到类 ConcreteRepository,其中 ConcreteRepository 实现 IRepository 和 EntityType 实现 IEntityType.我试过这个:

I'm fairly new to Ninject, and found myself stumbling when I came to implement a generic repository pattern. I want to bind a dependency IRepository<IEntityType> to a class ConcreteRepository<EntityType> where ConcreteRepository<T> implements IRepository<T> and EntityType implements IEntityType. I tried this:

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

...但 Ninject 不会接受,因为它不知道或不关心 EntityType 实现 IEntityType.我该如何绑定这个依赖项?

...but Ninject won't take that because it doesn't know or care that EntityType implements IEntityType. How can I go about binding this dependency?

更新

这是我得到的错误:

错误 3 类型ICM.Dependency.Repository.ConcreteRepository"不能用作泛型类型或方法Ninject.Syntax.IBindingToSyntax.To()"中的类型参数TImplementation".没有从ConcreteRepository"到IRepository"的隐式引用转换.

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()'. There is no implicit reference conversion from 'ConcreteRepository<EntityType>' to 'IRepository<IEntityType>'.

解决方案

我仍然不太明白为什么我的绑定不起作用,但显然我在那里错误地使用了泛型.因此,该解决方案与 NInject 并不真正相关.我结束了指定 ConcreteRepository 以显式连接 IEntityType 与 TEntityType:

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. I ended specifying the ConcreteRepository to explicitly connect IEntityType with TEntityType:

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

那么注入可以写成:

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

推荐答案

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

如果你想在这里看看我的:http://blog.staticvoid.co.nz/2011/10/staticvoid-repository-pattern-nuget.html 我有绑定示例

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

您收到的错误是说您的具体存储库不是您要绑定到的通用存储库的实例,即您需要这样做

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

不是

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

这篇关于如何在 Ninject 中绑定泛型接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆