例如,我有 2 个接口(interface) IInterface1
和 IInterface2
,
public interface IInterface1 {...}
public interface IInterface2 {...}
以及这些接口(interface)的一个实现 ImplClass
。
public class ImplClass : IInterface1, IInterface2 {...}
我必须确保应用程序只有一个 ImplClass 实例,它将用作 IInterface1 和 IInterface2。 我正在使用 ninject 进行依赖注入(inject)。所以我的问题是:下面的代码是否满足我的要求?
...
Bind<IInterface1>().To<ImplClass>().Using<SingletonBehavior>();
Bind<IInterface2>().To<ImplClass>().Using<SingletonBehavior>();
...
或者这段代码会为 eash 接口(interface)创建 2 个 ImplClass 实例?
最佳答案
使用 Ninject,您可以做到这一点:
var impl = new Impl();
container.Bind<IInt1>().ToMethod(c => impl);
container.Bind<IInt2>().ToMethod(c => impl);
当 Impl
类具有您无法注入(inject)的依赖项时,您可以这样做:
container.Bind<Impl>().ToSelf().InSingletonScope();
container.Bind<IInt1>().ToMethod(c => c.Kernel.Get<Impl>());
container.Bind<IInt2>().ToMethod(c => c.Kernel.Get<Impl>());
干净整洁。
关于c# - 将一个类绑定(bind)到多个接口(interface)作为单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4195428/