确定MediatR通知处理程序是否实现了自定义接口

问题描述 投票:0回答:1

我正在使用MediatR发布通知。

我已经定义了一个通知处理程序如下:

public class TestNotificationHandler : INotificationHandler<TestNotification>, IWithinTransaction
{
    public Task Handle(TestNotification notification, CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

然后我创建了一个自定义的Mediatr发布者,展示了here。发生的情况是,在Publisher类中,根据所选策略,调用一个特定的实现来调用已注册的事件处理程序,例如,对于SyncStopOnException策略:

private async Task SyncStopOnException(IEnumerable<Func<Task>> handlers)
{
    foreach (var handler in handlers)
    {                                
        await handler().ConfigureAwait(false);                                
     }
 }

实际上,在foreach中我正确地返回了TestNotificationHandler的处理程序,并且它被执行了。所以这很好。

但现在我想过滤这些处理程序,以便只执行实现我的自定义IWithinTransaction接口的那些处理程序。

这就是我遇到麻烦的地方。因为处理程序是System.Func类型。

所以问题是:如何确定处理程序所属的通知处理程序是否实现了此接口?唯一接近的是handler.Target属性,但我不知道如何使用它或检查它是否正在实现我的界面。

enter image description here

任何提示都会很棒:)

c# asp.net-core cqrs mediatr
1个回答
0
投票

我刚发现它。

private async Task SyncStopOnException(IEnumerable<Func<Task>> handlers)
    {
        foreach (var handler in handlers)
        {
            object target = handler.Target;
            if (target != null)
            {
                var xField = target.GetType().GetFields().Single(f => f.Name == "x");
                var xFieldValue = xField.GetValue(target);
                if (xFieldValue as IWithinTransaction != null)
                {

                }
            }

            await handler().ConfigureAwait(false);                                
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.