我正在尝试注册所有与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调试器。
有什么想法吗?
答案 0 :(得分:4)
您应该使用基于约定的组件注册
BasedOnDescriptor processes = AllTypes.FromAssembly(assemblyWithProcesses)
.BasedOn(typeof (IProcess<,>))
.WithService.AllInterfaces()
.Configure(x => x.LifeStyle.Transient);
container.Register(processes)
编辑删除了@ Krzysztof-kozmic提到的第一个样本
答案 1 :(得分:2)
如果您为多项服务注册了单个组件,我认为您必须手动为每个注册命名。
container.Register(
Component.For(procInterface)
.ImplementedBy(procType)
.LifeStyle.Transient
.Named(component.Implementation.FullName
+ "-"
+ procInterface.Name)
);
这应该按类型的全名注册每个组件加上您注册的界面。