是否可以使用裝飾類來爲每個具有Autofac和MediatR的事件處理程序創建LifeTimeScope?是否有可能使用Autofac和MediatR使用裝飾類來爲每個事件處理程序創建LifeTimeScope
所以我們有兩個Eventhandlers監聽同一個事件。 裝飾者應該創建一個LifteTimeScope,解析裝飾的事件處理器並調用裝飾的事件處理器的Handle方法。 我發現很多使用CommandHandlers的例子。 我玩過類似於下面顯示的代碼。 但我不能讓它工作。有些帖子還建議製作一個autofac註冊源。 IHAVE放在這裏提琴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);
}
}
}
也許我沒有正確理解這個問題,但是你看了Autofac委託工廠,因爲事件只是一個委託的特定形式? – Eris
嗨埃里斯Thx響應。是的,我已經看到了它。 autofac自動支持Func以及服務也具有代理工廠的示例。我只是想知道如果一個工廠將解決在裝飾器中創建的lifetimescope中的服務。也許你認爲裝飾器在其構造函數中使用了Func >作爲依賴項? –