我正在尝试注册所有与Windsor实现IProcess<T1, T2>
接口的类。为了完成这个任务,我在安装程序中添加了以下代码:
// Register all implemented process interfaces
var procTypes = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => x.IsDerivedFromOpenGenericType(typeof(IProcess<,>)))
.ToList();
foreach (var procType in procTypes)
foreach (var procInterface in procType.GetInterfaces().Where(x => x.IsDerivedFromOpenGenericType(typeof(IProcess<,>))))
container.Register(Component.For(procInterface).ImplementedBy(procType).LifeStyle.Transient);
我想注册的一个类如下:
public class PositionProcesses
: IProcess<CreatePositionParams, PositionDisplayViewModel>,
IProcess<EditPositionParams, PositionDisplayViewModel>
{
}
第一个接口被正确注册,但是在注册由这个类实现的第二个接口时,我得到了以下错误:
Test method MyJobLeads.Tests.Controllers.PositionControllerTests.Windsor_Can_Resolve_PositionController_Dependencies threw exception:
Castle.MicroKernel.ComponentRegistrationException: There is a component already registered for the given key MyJobLeads.DomainModel.Processes.Positions.PositionProcesses
在第一次循环迭代时,我的变量是:
+ procInterface {Name = "IProcess`2" FullName = "MyJobLeads.DomainModel.Data.IProcess`2[[MyJobLeads.DomainModel.ProcessParams.Positions.CreatePositionParams, MyJobLeads.DomainModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[MyJobLeads.DomainModel.ViewModels.Positions.PositionDisplayViewModel, MyJobLeads.DomainModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"} System.Type {System.RuntimeType}
+ procType {Name = "PositionProcesses" FullName = "MyJobLeads.DomainModel.Processes.Positions.PositionProcesses"} System.Type {System.RuntimeType}
第二行:
+ procInterface {Name = "IProcess`2" FullName = "MyJobLeads.DomainModel.Data.IProcess`2[[MyJobLeads.DomainModel.ProcessParams.Positions.EditPositionParams, MyJobLeads.DomainModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[MyJobLeads.DomainModel.ViewModels.Positions.PositionDisplayViewModel, MyJobLeads.DomainModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"} System.Type {System.RuntimeType}
+ procType {Name = "PositionProcesses" FullName = "MyJobLeads.DomainModel.Processes.Positions.PositionProcesses"} System.Type {System.RuntimeType}
(这两个都来自VS调试器。
任何想法?
你应该使用基于约定的组件注册
BasedOnDescriptor processes = AllTypes.FromAssembly(assemblyWithProcesses)
.BasedOn(typeof (IProcess<,>))
.WithService.AllInterfaces()
.Configure(x => x.LifeStyle.Transient);
container.Register(processes)
EDIT删除了@Krzysztof-kozmic提到的第一个样本
如果你有一个为多个服务注册的组件,我认为你必须手动命名每个注册。
见:http://docs.castleproject.org/Windsor.Registering-components-by-conventions.ashx Configuring_registration_13
container.Register(
Component.For(procInterface)
.ImplementedBy(procType)
.LifeStyle.Transient
.Named(component.Implementation.FullName
+ "-"
+ procInterface.Name)
);
这应该按照类型的全名加上要为其注册的接口注册每个组件。