当使用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的单个实例?
最有可能的是,如果其中两个组件中可能包含一个组件,则您的约定不好。但是从这样一个抽象的场景中无法分辨。您应该考虑一下,例如使用命名约定:
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());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句