是否可以使用装饰器类使用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 );
}
}
}
答案 0 :(得分:0)
是的,可能。
最后我想出了一个解决方案。代码可以在这里看到https://dotnetfiddle.net/fw4IBw
它涉及以下注册步骤
迭代所有eventhandler类型并将其注册为 命名(“EventHandler”,eventHandlerType)和 .InstancePerMatchingLifetimeScope(“PerHandlerKey”);
在同一循环获取通知类型
在EventHandlerDecorator中执行..