当使用在命名空间内而不在外部时,无法通过反射找到类。为什么?

时间:2017-05-16 10:05:30

标签: c# .net reflection namespaces using

我们有一些处理程序,这些处理程序通过反射在IoC中实例化,因为它们无法被引用。这很好用,直到我使用StyleCop并在命名空间内移动了一些处理程序。突然间,我们的算法无法获得特定命令的处理程序。我发现这个看似微不足道的变化确实让我们休息了。

变更前的处理程序:

using System;
using System.Threading;
using System.Threading.Tasks;

using AccessManagement.Common.Configuration;
using AccessManagement.DirectoryServices;
using AccessManagement.Management.AdContact.Commands;
using AccessManagement.Management.AdUser;
using AccessManagement.{NotForYourEyes1};
using AccessManagement.{NotForYourEyes1}.Enums;
using AccessManagement.{NotForYourEyes1}.Extensions;
using AccessManagement.{NotForYourEyes1}.Models;

using Architecture.Core;

using {NotForYourEyes2}.Common;
using {NotForYourEyes2}.Common.Configuration;

namespace AccessManagement.Management.AdContact
{


    [EnableHandler]
    public class MoveAdContactHandler : IHandleRequest<MoveAdContact, AdUserResponse>
    {
        public Task<AdUserResponse> Handle(MoveAdContact request, CancellationToken cancellationToken = new CancellationToken())
        {

变更后的处理程序:

namespace AccessManagement.Management.AdContact
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    using AccessManagement.Common.Configuration;
    using AccessManagement.DirectoryServices;
    using AccessManagement.Management.AdContact.Commands;
    using AccessManagement.Management.AdUser;
    using AccessManagement.{NotForYourEyes1};
    using AccessManagement.{NotForYourEyes1}.Enums;
    using AccessManagement.{NotForYourEyes1}.Extensions;
    using AccessManagement.{NotForYourEyes1}.Models;

    using Architecture.Core;

    using {NotForYourEyes2}.Common;
    using {NotForYourEyes2}.Common.Configuration;

    [EnableHandler]
    public class MoveAdContact2Handler : IHandleRequest<MoveAdContact, AdUserResponse>
    {

向IoC容器注册处理程序的算法:

    private static void RegisterBusHandlers(IServiceRegistry serviceRegistry, Func<ILifetime> handlersLifetime)
    {
        var handlerProvider = new HandlerRegistrator((i, t) =>
        {
            serviceRegistry.Register(i, t, handlersLifetime());
        });

        var handlerTypes =
        AppDomain.CurrentDomain
                    .GetAssemblies()
                    .SelectMany(a => a.GetTypes())
                    .Where(t => t.GetCustomAttribute<EnableHandlerAttribute>() != null);

        foreach (var handlerType in handlerTypes)
        {
            handlerProvider.RegisterHandler(handlerType);
        }
    }

总结 - 在找到更改之前的处理程序,根本找不到更改后的处理程序。对我和我的团队来说,这是一种大脑扭曲。有人能解释一下这种行为吗?

1 个答案:

答案 0 :(得分:4)

在考虑封闭名称空间之前,现在将使用那些using指令。您可能习惯于在AccessManagement.ManagementAccessManagement内定位类型,现在改为将这些类型名称解析为由using指令声明的名称空间中的类型。

哪些,只有你可以确定。

E.g。如果有两种不同的EnableHandlerAttribute类型,那么您的注册码现在可能现在注册完全不同的类型。