问题
interface IService<T> {}
class ConcreteServiceA<T> : IService<T> {}
I need that:
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();
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>>()
Any ideas?
回答1:
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
来源:https://stackoverflow.com/questions/40125455/ninject-bind-multiple-types-to-the-same-singleton-instance