3

所以我们有两个 Eventhandlers 监听同一个事件。装饰器应该创建一个 LifteTimeScope,解析装饰事件处理程序并调用装饰事件处理程序的 Handle 方法。我发现了很多使用 CommandHandlers 执行此操作的示例。但那里更容易,因为每个命令只有一个处理程序。不太多。所以问题是如何在 autofac 中注册事件处理程序和装饰器!

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

class EventHandlerB : IAsyncNotification<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

0 回答 0