gpt4 book ai didi

c# - 在现有框架中调整/包装 MediatR 通知

转载 作者:行者123 更新时间:2023-11-30 16:41:19 25 4
gpt4 key购买 nike

TL;DR 我如何调整现有的一组事件/通知和相关处理程序,以便 MediatR 可以使用它们,而不必为每个现有类型实现额外的处理程序和通知?

长版:我们目前有一个用于调度事件的系统,我们在其中使用总线实现来进行实际传输。

我目前正在试验一种进行中的变体。与 MediatR 的 INotification 非常相似我们有一个标记界面 IEvent同样类似于 INotificationHandler<in INotification> MediatR 我们有一个 IEventHandler<in IEvent>

我们使用 Autofac 来注册我们的 EventHandlers,然后我们在实际从总线上消费时进行一些反射。

我想做的是实现某种通用适配器/包装器,以便我可以保留现有的事件和事件处理程序,并在从 MediatR 发送通知时使用它们,基本上减少了我的现有代码围绕设置容器进行了大量更改。

就代码而言,我想让以下类的行为就好像它在使用 MediatR 接口(interface)一样。

public class MyHandler : IEventHandler<SampleEvent>
{
public Task Handle(SampleEvent input) => Task.CompletedTask;
}

有什么建议吗?

最佳答案

现状

所以现在您的代码如下所示:

public class SampleEvent : IEvent
{
}

public class SampleEventHandler : IEventHandler<SampleEvent>
{
public Task Handle(SampleEvent input) => Task.CompletedTask;
}

使事件与 MediatR 兼容

我们需要 MediatR 识别的事件,这意味着他们需要实现 INotification .

这样做的第一种方法是使您的 IEvent界面工具INotification .这样做的好处是几乎没有代码更改,它使您所有当前和新的事件都与 MediatR 兼容。可能不太好的事情是您当前执行 IEvent 的程序集。 live 需要依赖 MediatR。

public interface IEvent : INotification
{
}

如果这不可行,我看到的第二种方法是创建新的、特定于 MediatR 的类,这些类继承自现有的并实现 INotification .这意味着您需要为每个现有类创建一个适配器类,但您可以将现有项目从 MediatR 依赖项中解放出来。

// Lives in AssemblyA
public class ExistingEvent : IEvent
{
}

// Lives in AssemblyB that has a dependency on both
// AssemblyA and MediatR
public class MediatrExistingEvent : ExistingEvent, INotification
{
}

连接处理程序

无论您在上一步中采用哪种方式,您现在所处的状态是您拥有同时实现 IEvent 的类。和 INotification ,并且您有实现 IEventHandler<in T> where T : IEvent 的处理程序.

我们可以创建一个适配器类来满足 MediatR 的 API,并将工作委托(delegate)给您现有的处理程序:

public class MediatrAdapterHandler<T> : INotificationHandler<T>
where T : IEvent, INotification
{
private readonly IEventHandler<T> _inner;

public MediatrAdapterHandler(IEventHandler<T> inner)
{
_inner = inner;
}

public Task Handle(T notification) => _inner.Handle(notification);
}

最后就是在Autofac容器中注册这个类。鉴于您现有的处理程序已注册为 IEventHandler<T> ,这很容易完成:

builder
.RegisterGeneric(typeof(MediatrAdapterHandler<>))
.As(typeof(INotificationHandler<>));

每次你现在向容器询问一个 INotificationHandler<T> 的实例, 它将创建 MediatrAdapterHandler<T> 的一个实例其中您对 IEventHandler<T> 的原始实现将被注入(inject)。

关于c# - 在现有框架中调整/包装 MediatR 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49586478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com