如何使用泛型类型参数调用泛型方法

How to call generic methods with generic type parameter

它比 NInject 更多关于泛型,但我很好奇。

以下工作正常

kernel.Bind(typeof(IEntityRepository<,>)).To(typeof(LoggerRepository<,>));

但是如果我想使用泛型呢?以下给我编译时错误.

kernel.Bind<IEntityRepository<,>>().To<LoggerRepository<IEntity<>,int>();

kernel.Bind<IEntityRepository<,>>().To<LoggerRepository<,>();

我确定我遗漏了一些非常简单的东西,并且一定在 ST 的某个地方得到了回答。有人可以直接告诉我答案吗?

编辑:以下工作正常

kernel.Bind<IEntityRepository<AppUser, int>>().To<EntityRepository<AppUser, int>>();

但我想应该有一种方法可以不指定类型(AppUse 和 int)。

当没有指定泛型的所有类型参数时,它们不能用在除 typeof() 之外的任何表达式中。这篇文章可能对您有所帮助:Unbound Generics: an Open and Closed Case

我特别指的是这部分,它讨论了未绑定泛型与依赖注入的结合使用:

When you use code to perform the registration, you also omit the type parameters; for example RegisterType(typeof(MyTypes.IMyInterface<,>)). As you saw earlier, Microsoft says that "the typeof operator can operate on unbound generic types (generic types that do not yet have specific type arguments)"

编辑:

一般来说,将未绑定泛型与依赖注入一起使用会导致代码混乱且难以阅读。如果我没记错的话,你正试图这样做是因为你可以对类型参数施加约束。

但为什么不为您要使用的类型定义一个父接口呢?当然,您会失去约束,但在这种情况下它们真的有必要吗?您已经在一个位置控制绑定,即您的 DI 容器。当您的泛型类型通过其他人将使用的 API 公开时,主要使用约束。通常,客户端无论如何都不会通过 DI 容器连接这些代码,因为它们要么使用派生的 类、工厂,要么只是直接实例化它。

你想这样做有什么特别的原因吗?

编辑#2:

也许您正在寻找这个?

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

然后,当您在调用代码中将 IRepository<SomeEntity> 作为构造函数参数时,ninject 将在 运行 时为您解析为 Repository<SomeEntity>