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

时间:2017-06-02 21:15:10

标签: c# autofac mediatr

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

所以我们有两个Eventhandler监听同一个事件。 装饰器应该创建一个LifteTimeScope,解析装饰的事件处理程序并调用装饰的事件处理程序的Handle方法。 我发现很多用CommandHandlers做这个的例子。 我玩过类似下面所示的代码。 但我不能让它发挥作用。一些帖子还建议制作autofac registrationsource。 我在这里放了一个小提琴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 );
        }
    }
}

1 个答案:

答案 0 :(得分:0)

是的,可能。

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

它涉及以下注册步骤

  1. 迭代所有程序集并获取所有eventHandler类型
  2. 迭代所有eventhandler类型并将其注册为         命名(“EventHandler”,eventHandlerType)和         .InstancePerMatchingLifetimeScope(“PerHandlerKey”);

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

  4. 在同一个循环寄存器中 eventhandlerFactory每个eventhandler AsSelf和as implementedInterfaces
  5. 在同一个循环寄存器中只有一个 每个通知类型的eventHandlerDecorator .Named( “EventHandlerDecorator”,interfaceType ).AsSelf()InstancePerLifetimeScope();
  6. 对于MultiInstanceFactory,只解析一个装饰器 通知c.ResolveKeyed(“EventHandlerDecorator”......
  7. 在EventHandlerDecorator中执行..

    1. 解析NotificationType的所有工厂
    2. 为每个工厂创建每个处理程序lifetimescope
    3. 创建处理程序
    4. 调用处理程序
相关问题