Ninject: 将多个类型绑定到同一个单例实例

Ninject: Bind multiple types to the same singleton instance

interface IService<T> {}

class ConcreteServiceA<T> : IService<T> {}

我需要:

IService<string> stringServices = kernel.Get<IService<string>>();
ConcreteServiceA<string> concreteStringServiceA = kernel.Get<ConcreteServiceA<string>>();

Assert.IsSameReference(stringService, concreteStringServiceA);

到目前为止,我已尝试创建绑定:

this.Bind(typeof(IService<>))
    .To(typeof(ConcreteServiceA<>))
    .InSingletonScope();

this.Bind(typeof(ConcreteServiceA<>)).ToSelf().InSingletonScope();

尽管如此,当我请求 IService<string>ConcreteServiceA<string> 时,使用此绑定我得到两个不同的实例:

kernel.Get<IService<string>>() instance is different of kernel.Get<ConcreteService<string>>()

有什么想法吗?

您可以指定多个类型同时绑定,例如:

this.Bind(typeof(IService<>), typeof(ConcreteServiceA<>))
    .To(typeof(ConcreteServiceA<>))
    .InSingletonScope();

我做了一些测试来证实这一点:

kernel.Bind(typeof(IList<>)).To(typeof(List<>)).InSingletonScope();
kernel.Bind(typeof(List<>)).ToSelf().InSingletonScope();

var list1 = kernel.Get<IList<string>>();
var list2 = kernel.Get<List<string>>();

Assert.IsTrue(list1.Equals(list2)); // fails as per your question


kernel.Bind(typeof(IList<>), typeof(List<>)).To(typeof(List<>)).InSingletonScope();

var list1 = kernel.Get<IList<string>>();
var list2 = kernel.Get<List<string>>();

Assert.IsTrue(list1.Equals(list2)); // passes