本文介绍了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);
到目前为止,我尝试创建绑定:
Up to now, I've tried to create bindings:
this.Bind(typeof(IService<>))
.To(typeof(ConcreteServiceA<>))
.InSingletonScope();
this.Bind(typeof(ConcreteServiceA<>)).ToSelf().InSingletonScope();
不过,使用此绑定,当我请求IService<string>
和ConcreteServiceA<string>
时,我得到了两个不同的实例:
Nevertheless, using this binding I'm getting two different instances when i request for a IService<string>
and for a ConcreteServiceA<string>
:
kernel.Get<IService<string>>() instance is different of kernel.Get<ConcreteService<string>>()
有什么想法吗?
推荐答案
您可以指定多个类型以同时绑定,例如:
You can specify multiple types to bind at the same time, e.g.:
this.Bind(typeof(IService<>), typeof(ConcreteServiceA<>))
.To(typeof(ConcreteServiceA<>))
.InSingletonScope();
我进行了一些测试以确认这一点:
Some tests I made to confirm this:
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
这篇关于Ninject:将多个类型绑定到同一个单例实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!