通过事件订阅模式进行相应的操作,观察者模式

首先事件订阅模式的传入需要添加一个新的类
    /// <summary>
    /// 删除任务时触发的消息事件。
    /// </summary>
    public class AppTaskDeleteEventArgs : IEvent
    {
        public long TaskId { get; set; }
    }

当然每个事件都需要一个不同的类,否则事件总线无法识别你具体做什么

然后再你做相应操作的时候进行一个消息的发布

        /// <summary>
        /// 通过递归的方式删除记录的子记录
        /// </summary>
        /// <param name="mongo"></param>
        /// <param name="taskId"></param>
        private async Task DeleteChild(IMongoCollection<AppTaskEntity> mongo, long taskId)
        {
            var filter = Builders<AppTaskEntity>.Filter.Eq(x => x.ParentId, taskId);
            var childCollection = mongo.FindList(filter);
            foreach (var chind in childCollection)
            {
                await mongo.DeleteAsync(chind.RecordId);
                await this.DeleteChild(mongo, chind.RecordId);
            }
//这个_eventBus.需要先进行注入
        private readonly IEventBus _eventBus;
//构造函数中也要添加
            await _eventBus.Publish(new AppTaskDeleteEventArgs() { TaskId = taskId });
        }

然后再相应的模块中添加相应的操作,这种模式叫做观察者模式,对事件进行监听,一但收到消息的发布,就进行相应的操作

        async Task IEventHandler<AppTaskDeleteEventArgs>.Handle(EventContext<AppTaskDeleteEventArgs> context)
        {
            await this.DeleteAsync(x => x.TaskId == context.Message.TaskId);
        }

 

posted @ 2022-05-05 10:01  咳咳Pro  阅读(33)  评论(0)    收藏  举报