使用ninject.extensions.conventions服务绑定多次 [英] Service bound multiple times using ninject.extensions.conventions
问题描述
在使用ninject约定绑定了多个接口,我得到了以下的问题所有的实现:
When using ninject conventions to bind all implementations of several interfaces I got the following problem:
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>());
我应该如何配置以获取服务
ninjected?
How should I configure the bindings in order to get only a single instance of Service
ninjected?
推荐答案
大多数likly你的约定是不好的,如果有一个组件,它可以在其中的两个。但不可能从这样一个抽象的情景告诉。你应该想想,例如使用命名约定:
Most likly your conventions is not good if there is a component that can be in two of them. But it is impossible to tell from such a abstract scenario. You should think about that, E.g. use naming conventions:
kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses().EndingWith("Service").
BindAllInterfaces());
或引入一个基本接口:
or introduce a base interface:
kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses().InheritedFrom<IService>().
BindAllInterfaces());
或引入一个属性,通过命名空间选择,....方法有很多种。一个另一种选择是在两个步骤中选择的类:
or introduce an attribute, select by namespace, .... There are many ways. An other option is to select the classes in two steps:
kernel.Bind(x => x
.FromThisAssembly().SelectAllClasses().InheritedFrom<IServiceA>()
.Join().FromThisAssembly().SelectAllClasses().InheritedFrom<IServiceB>().
BindAllInterfaces());
如果服务类型配置不同,您可以排除特殊情况下,在绑定之一:
If the service types are configured differently you can Exclude the special case in one of the bindings:
kernel.Bind(x => x
.FromThisAssembly().SelectAllClasses().InheritedFrom<IServiceA>()
.Exclude<Service>().
BindAllInterfaces());
这篇关于使用ninject.extensions.conventions服务绑定多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!