编程语言
首页 > 编程语言> > c# – 为什么我不能在Windsor中为多个接口注册一个类?

c# – 为什么我不能在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)

编辑删除了@ Krzysztof-kozmic提到的第一个样本

标签:c,reflection,castle-windsor
来源: https://codeday.me/bug/20190530/1186127.html