是否可以使用Decorator类使用AutoFac和MediaTR创建每个EventHandler的LifetimesC



是否可以使用AutoFac和MediaTR使用Decorator类创建每个EventHandler的LifeTimesCope?

因此,我们有两个事件手听相同的事件。装饰器应该会创建电梯尺寸,解决装饰的事件手并调用装饰的EventHandler的手柄方法。我发现了很多与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 );
        }
    }
}

是的。

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

它涉及注册以下步骤

  1. 迭代您的所有组件并获取所有EventHandler类型
  2. 迭代所有EventHandler类型,并将其注册为 命名(" EventHandler",EventHandLertype(和 .InstancePerMatchingLifetimesCope(" PerhandlerKey"(;

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

  4. 在同一循环注册中eventhandlerFactory avereverhandler asself和as实施Interedinterfaces
  5. 在同一循环中只有一个eventHandlerDecorator per Notification类型。" EventHandlerDecorator",InterFaceType(.asself((。instancePerliFetimesCope((;
  6. 用于多InstanceFactory仅解决一个装饰器通知C.ResolveKeyed(" EventHandlerDecorator" ...

在EventHandlerDecorator中做..

  1. 解决通知类型的所有工厂
  2. 对于每个工厂,每个处理程序lifetimesscope
  3. 创建处理程序
  4. 调用处理程序

最新更新