是否可以使用装饰器类使用 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 );
}
}
}