当使用ninject约定来绑定多个接口的所有实现时,我遇到了以下问题:
public interface IServiceA { }
public interface IServiceB { }
public class Service : IServiceA, IServiceB { }
public class FooA
{
public Foo(IEnumerable<IServiceA> a)
{
// a has 2 instances of Service
}
}
public class FooB
{
public Foo(IEnumerable<IServiceB> b)
{
// b has 2 instances of Service
}
}
// ...
kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses().InheritedFrom<IServiceA>().
BindAllInterfaces());
kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses().InheritedFrom<IServiceB>().
BindAllInterfaces());
var a = new FooA(kernel.GetAll<IServiceA>());
var b = new FooB(kernel.GetAll<IServiceB>());
我应该如何配置绑定才能获得Service
ninjected的单个实例?
答案 0 :(得分:2)
如果有一个组件可以在其中两个组件中,那么大多数情况下你的约定都不好。但是从这样一个抽象的场景中无法分辨出来。你应该考虑一下,例如使用命名约定:
kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses().EndingWith("Service").
BindAllInterfaces());
或引入基础界面:
kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses().InheritedFrom<IService>().
BindAllInterfaces());
或引入属性,按名称空间选择,....有很多方法。另一个选择是分两步选择类:
kernel.Bind(x => x
.FromThisAssembly().SelectAllClasses().InheritedFrom<IServiceA>()
.Join().FromThisAssembly().SelectAllClasses().InheritedFrom<IServiceB>().
BindAllInterfaces());
如果服务类型的配置不同,您可以在其中一个绑定中排除特殊情况:
kernel.Bind(x => x
.FromThisAssembly().SelectAllClasses().InheritedFrom<IServiceA>()
.Exclude<Service>().
BindAllInterfaces());