1

是否可以使用装饰器类使用 Autofac 和 MediatR 创建每个事件处理程序的 LifeTimeScope?

所以我们有两个 Eventhandlers 监听同一个事件。装饰器应该创建一个 LifteTimeScope,解析装饰事件处理程序并调用装饰事件处理程序的 Handle 方法。我发现了很多使用 CommandHandlers 执行此操作的示例。我玩过类似于下面显示的代码。但我不能让它工作。一些帖子还建议制作一个 autofac 注册源。我在这里放了一个小提琴https://dotnetfiddle.net/fw4IBw

class EventHandlerA : IAsyncNotificationHandler<AnEvent>
{ 
     public void Handle(AnEvent theEvent)
     {
     }
}

class EventHandlerB : IAsyncNotificationHandler<AnEvent>
{ 
     public void Handle(AnEvent theEvent)
     {
     }
}

/// <summary>
///  Wraps inner Notification Handler in Autofac Lifetime scope named 
     PerEventHandlerScope"
/// </summary>
/// <typeparam name="TNotification"></typeparam>
public class LifetimeScopeEventHandlerDecorator<TNotification> :
    IAsyncNotificationHandler<TNotification> where TNotification : class, 
              IAsyncNotification
{
    private readonly ILifetimeScope _scope;
    private readonly Type _decoratedType;

    /// <summary>
    /// Const Name of Scope that dependencies can Match using       
     PerMatchingLifeTimeScope(LifetimeScopeEventHandlerDecorator.ScopeName)
    /// </summary>
    public const string ScopeName = LifeTimeScopeKeys.PerHandlerKey;

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="scope"></param>
    public LifetimeScopeEventHandlerDecorator( ILifetimeScope scope, Type 
          decoratedType )
    {
        _decoratedType = decoratedType;
        _scope = scope;
    }

    /// <summary>
    /// Wraps inner Notification Handler in Autofac Lifetime scope
    /// </summary>
    /// <param name="notification"></param>
    /// <returns></returns>
    public async Task Handle( TNotification notification )
    {
        using ( var perHandlerScope = _scope.BeginLifetimeScope( 
         LifeTimeScopeKeys.PerHandlerKey ) )
        {
            var decoratedHandler =
   perHandlerScope.ResolveKeyed<IAsyncNotificationHandler<TNotification>>( 
              "IAsyncNotificationHandlerKey" );
            await decoratedHandler.Handle( notification );
        }
    }
}
4

1 回答 1

0

是的,有可能。

最后我想出了一个解决方案。代码可以在这里看到 https://dotnetfiddle.net/fw4IBw

它涉及以下注册步骤

  1. 迭代所有程序集并获取所有 eventHandler 类型
  2. 迭代所有事件处理程序类型并将它们注册为 Named("EventHandler", eventHandlerType) 和 .InstancePerMatchingLifetimeScope("PerHandlerKey" );

  3. 在同一循环中获取通知类型

  4. 在同一个循环中,为每个事件处理程序 AsSelf 注册一个 eventhandlerFactory 并作为implementedInterfaces
  5. 在同一循环中,每个通知类型仅注册一个 eventHandlerDecorator .Named( "EventHandlerDecorator", interfaceType ).AsSelf().InstancePerLifetimeScope();
  6. 对于 MultiInstanceFactory,只为通知解析一个装饰器 c.ResolveKeyed("EventHandlerDecorator"...

在 EventHandlerDecorator 做..

  1. 解析 NotificationType 的所有工厂
  2. 为每个工厂创建每个处理程序生命周期
  3. 创建处理程序
  4. 调用处理程序
于 2017-06-06T06:53:26.807 回答