ninject 中的嵌套通用通配符绑定

Nested generic wildcard binding in ninject

是否有一种干净的方法来绑定到 Ninject 中的嵌套泛型 "wildcard"?

我知道我可以通过以下绑定请求任意 IThing<T>

kernel.Bind(typeof(IThing<>)).To(typeof(Thing<>));

然而,我真正想要的是任意IThing<Foo<T>>。以下在句法上不起作用:

kernel.Bind(typeof(IThing<Foo<>>)).To(typeof(FooThing<>));

这在句法上有效:

kernel.Bind(typeof(IThing<>).MakeGenericType(typeof(Foo<>))).To(typeof(FooThing<>));

但是 ninject 不知道该怎么办。 Ninject能做到这种事吗?

简单的回答是:不,你不能用 Ninject 做到这一点。事实上,唯一真正支持这种使用部分封闭泛型类型的复杂绑定的 DI 库是 Simple Injector。在 Simple Injector 中你可以这样做:

container.RegisterOpenGeneric(
    typeof(IThing<>),
    typeof(Thing<>).MakeGenericType(typeof(Foo<>)));

在您的示例中,您有一个 FooThing<T>,它可能包含如下嵌套类型约束:

public class FooThing<T> : IThing<Foo<T> { }

同样,Ninject 不支持这一点。我相信 Autofac 在某种程度上对此有一些支持,但只有 Simple Injector 能够为您解决几乎所有奇怪和复杂的泛型类型约束的类型。在 Simple Injector 中,注册很简单:

container.RegisterOpenGeneric(typeof(IThing<>), typeof(FooThing<>));

当请求 IThing<Foo<int>> 时,Simple Injector 会发现它必须解析 FooThing<int>