参考 https://aspnetboilerplate.com/Pages/Documents/EventBus-Domain-Events
EventBus
The EventBus is a singleton object that is shared by other classes to trigger and handle events. To use the event bus, you need to get a reference to it. You can do that in two ways.
1. 事件总线是单例对象
2. 如何使用
a).Injecting IEventBus 使用属性注入模式:
参考代码:
public class TaskAppService : ApplicationService { public IEventBus EventBus { get; set; } public TaskAppService() { EventBus = NullEventBus.Instance; } }
Property injection is more proper than a constructor injection when injecting the event bus. This way, your class can work without the event bus. NullEventBus implements the null object pattern. When you call its methods, it does nothing at all.
b).Getting The Default Instance 使用默认实例
这种是使用全局的 “event bus” 。
EventBus.Default.Trigger(...); //trigger an event
We do not recommend that you directly use EventBus.Default, since it makes unit testing harder.
官方说明是: 不推荐使用这种方式 “since it makes unit testing harder” 这会使得项目进行单元测试变得跟困难。。。 (我没去研究过为啥困难。。。暂且相信别人的经验吧。)
3. 定义事件
在触发事件之前,您需要先对其进行定义。事件由派生自EventData的类表示
参考代码:
public class TaskCompletedEventData : EventData { public int TaskId { get; set; } }
此类包含处理事件的类所需的属性。 EventData类定义EventSource(触发事件的对象)和EventTime(触发时)属性。
public class ActivityWriter : IEventHandler<TaskCompletedEventData>, ITransientDependency { public void HandleEvent(TaskCompletedEventData eventData) { WriteActivity("A task is completed by id = " + eventData.TaskId); } }
使用这种方式好处:abp框会将您实现的事件注册进依赖注入系统( ITransientDependency “Transient” 指的是生命周期),abp框依赖注入系统帮你管理事件生命周期。
a).处理基本事件
意思就是 A实现 IEventHandler<T> 后, B、C继承A ,那么B、C 两个事件会被注册。
public class ActivityWriter : IEventHandler<TaskCompletedEventData>, IEventHandler<TaskCreatedEventData>, ITransientDependency { public void HandleEvent(TaskCompletedEventData eventData) { //TODO: handle the event... } public void HandleEvent(TaskCreatedEventData eventData) { //TODO: handle the event... } }
7.注册事件处理程序
a).自动注册
实现了“IEventHandler” ,都会被abp框架自动注册。
b).手动注册
注意:为什么不推荐手动注册!
直接看官网:https://aspnetboilerplate.com/Pages/Documents/EventBus-Domain-Events#manually
注意:手动注册之后,如何释放被注册的事件!
8.后台事件
If you don't want to execute event handlers right away, you can queue events in a background job like below;
public class MyService { private readonly IBackgroundJobManager _backgroundJobManager; public MyService(IBackgroundJobManager backgroundJobManager) { _backgroundJobManager = backgroundJobManager; } public void Test() { _backgroundJobManager.EnqueueEventAsync(new MySimpleEventData()); } }
使用这种方法,将在执行后台作业时触发相关事件。