ABP VNext事件总线-本地事件
1、本地事件分为发布事件和订阅事件,其中,发布事件和订阅事件都必须要注册到ID中,使用接口 ITransientDependency 来注册,方便让事件总线发现并注册他们。
2、发布事件需要使用ID获取ILocalEventBus 服务,在定义一个发布方法之后,使用该服务的 PublishAsync() 方法来发布事件
// 定义一个本地事件
public class HelloEvent : LocalEto
{
public string Name { get; set; }
}
// 发布一个本地事件
public class HelloService : ApplicationService
{
private readonly ILocalEventBus _localEventBus;
public HelloService(ILocalEventBus localEventBus)
{
_localEventBus = localEventBus;
}
[UnitOfWork] // 添加这个属性来创建一个工作单元范围
public virtual async Task SayHelloAsync(string name)
{
// 发布一个本地事件
await _localEventBus.PublishAsync(new HelloEvent
{
Name = name
});
}
}
3、订阅事件需要继承ILocalEventHandler<发布实体Dto> ,和注入ID,ITransientDeoendency
// 订阅一个本地事件
public class HelloEventHandler : ILocalEventHandler<HelloEvent>, ITransientDependency // 使用这个接口来注册到依赖注入中
{
private readonly ILogger<HelloEventHandler> _logger;
public HelloEventHandler(ILogger<HelloEventHandler> logger)
{
_logger = logger;
}
public virtual Task HandleEventAsync(HelloEvent eventData) // 添加 virtual 关键字来确保正确调用
{
// 处理本地事件
_logger.LogInformation($"Hello, {eventData.Name}!");
return Task.CompletedTask;
}
}
最后:当触发发布事件SayHelloAsync方法后,订阅事件将会自动触发。完美!

浙公网安备 33010602011771号