Ninject: Bind multiple types to the same singleton instance

≯℡__Kan透↙ 提交于 2019-12-11 03:45:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!