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

时间:2016-10-19 08:00:08

标签: c# ninject

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>>()

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

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

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

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

#!/usr/bin/env nodejs