成员介绍:

IEventBus、EventBus:事件总线

IEventHandler、xxxEventHandler:事件处理程序

IEvent、xxxEvent:事件,一个事件可对应多个事件处理程序

EventHandlerAttribute:事件处理程序的特性,可添加排序信息等

EvnetHandlerMetadata:IEventHandler信息

EventHandlerMetadataItem:EventHandler实例信息

事件总线:

     public interface IEventBus
{
void Trigger<TEvent>(TEvent eventData, string topic = null) where TEvent : IEvent;
}
public class EventBus : IEventBus
{
private static System.Collections.Concurrent.ConcurrentDictionary<Type, EvnetHandlerMetadata> _evnetHandlerMetadatas
= new ConcurrentDictionary<Type, EvnetHandlerMetadata>();
private static readonly EventHandlerAttribute DefaultAttribute = new EventHandlerAttribute()
{
IgnoreError = false,
Priority = ,
Topic = null
}; static EventBus()
{ } public Func<Type, object> Activator { get; set; } /// <summary>
/// 触发事件
/// </summary>
/// <typeparam name="IEvent"></typeparam>
/// <param name="eventData"></param>
public void Trigger<TEvent>(TEvent eventData, string topic = null) where TEvent : IEvent
{ EvnetHandlerMetadata evnetHandlerMetadata = _evnetHandlerMetadatas.GetOrAdd(typeof(TEvent), (key) =>
{
var handlerType = typeof(IEventHandler<>).MakeGenericType(typeof(TEvent));
var handlerMetadata = new EvnetHandlerMetadata()
{
EventHandlerType = handlerType,
EventType = key,
Items = new List<EventHandlerMetadataItem>()
};
var handlerInstances = Activator.Invoke(typeof(IEnumerable<>).MakeGenericType(handlerType)) as IEnumerable;
foreach (var handlerInstance in handlerInstances)
{
var typeInfo = handlerInstance.GetType().GetTypeInfo();
var handleMethods = typeInfo.DeclaredMethods.Where(t => t.Name.EndsWith($"{key.Name}>.Handle") || t.Name == "Handle");
var method = handleMethods.FirstOrDefault();
if (method == null) continue;
var attr = method.GetCustomAttribute<EventHandlerAttribute>()
?? handlerInstance.GetType().GetCustomAttribute<EventHandlerAttribute>()
?? DefaultAttribute
;
handlerMetadata.Items.Add(new EventHandlerMetadataItem()
{
Method = method,
IgnoreError = attr.IgnoreError,
Priority = attr.Priority,
Type = handlerInstance.GetType()
});
}
handlerMetadata.Items = handlerMetadata.Items.OrderByDescending(p => p.Priority).ThenBy(x => x.Type.Name).ToList();
return handlerMetadata;
}); var handlers = evnetHandlerMetadata.Items
.WhereIf(p => p.Topic == topic, !string.IsNullOrEmpty(topic))
.Select(x => new { Instance = Activator.Invoke(x.Type), Meta = x })
.ToList()
;
foreach (var handler in handlers)
{
try
{
handler.Meta.Method.Invoke(handler.Instance, new object[] { eventData });
}
catch (Exception ex)
{
if (!handler.Meta.IgnoreError)
{
while (true)
{
if (ex.InnerException == null)
{
throw ex;
}
else
{
ex = ex.InnerException;
}
} }
}
}
} public class EventHandlerMetadataItem
{
public Type Type { get; set; }
public MethodInfo Method { get; set; }
public int Priority { get; set; }
public bool IgnoreError { get; set; }
public string Topic { get; set; } } public class EvnetHandlerMetadata
{
public List<EventHandlerMetadataItem> Items { get; set; }
public Type EventHandlerType { get; set; }
public Type EventType { get; set; } }
}

事件处理接口:

     /// <summary>
/// 事件处理接口
/// </summary>
/// <typeparam name="TEvent">继承IEvent对象的事件源对象</typeparam>
public interface IEventHandler<T> where T : IEvent
{
/// <summary>
/// 处理程序
/// </summary>
/// <param name="evt"></param>
void Handle(T evt);
} [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class EventHandlerAttribute : Attribute
{
/// <summary>
/// 执行优先级
/// </summary>
public int Priority { get; set; }
public bool IgnoreError { get; set; }
public string Topic { get; set; }
public EventHandlerAttribute()
{ }
}

public interface IEvent
{
}

具体事件处理:

     /// <summary>
/// 文件上传事件处理
/// </summary>
[EventHandler(Priority =, IgnoreError = true)]
public class FileUploadEventHandler : IEventHandler<FileUploadEvent>
{
private readonly IFeeService _feeService;
private readonly ILogger _logger; public FileUploadEventHandler(
IFeeService feeService,
ILogger<FileUploadEventHandler> logger
)
{
_feeService = feeService;
_logger = logger;
} public void Handle(FileUploadEvent evt)
{
// _logger.LogInformation(evt.FileName);
////扣减存储空间
//var useResult=_feeService.UseFeeItem(Enums.Finance_FeeItem.Storage, evt.FileSize, $"上传文件{evt.FileName}");
//if (!useResult.Success)
//{
// throw new Exception(useResult.Message);
//}
}
}

事件触发:

var eventBus = _serviceLocator.GetService<IEventBus>();
eventBus.Trigger(new FileUploadEvent() { OwnUserID = globalValue.User.ID, UserID = globalValue.User.OwnUserID, Url = uploadResult.Data.Url, FileName = file.FileName, FileSize = file.Length, FileType = fileType });

参考:https://www.cnblogs.com/lwqlun/p/10468058.html

EventBus事件总线(牛x版)的更多相关文章

  1. Guava - EventBus(事件总线)

    Guava在guava-libraries中为我们提供了事件总线EventBus库,它是事件发布订阅模式的实现,让我们能在领域驱动设计(DDD)中以事件的弱引用本质对我们的模块和领域边界很好的解耦设计 ...

  2. EventBus(事件总线)

    EventBus(事件总线) Guava在guava-libraries中为我们提供了事件总线EventBus库,它是事件发布订阅模式的实现,让我们能在领域驱动设计(DDD)中以事件的弱引用本质对我们 ...

  3. dhroid - eventbus 事件总线

    你听过onClick 事件,onItemClick 事件,事件总线不一定听过吧, eventbus 事件总线也是一个编程思想,为什么要设计EventBus了,因为他是领域驱动设计中比不可少的模块,它承 ...

  4. EventBus事件总线

    EventBus事件总线的使用-自己实现事件总线   在C#中,我们可以在一个类中定义自己的事件,而其他的类可以订阅该事件,当某些事情发生时,可以通知到该类.这对于桌面应用或者独立的windows服务 ...

  5. EventBus 事件总线 案例

    简介 地址:https://github.com/greenrobot/EventBus EventBus是一个[发布 / 订阅]的事件总线.简单点说,就是两人[约定]好怎么通信,一人发布消息,另外一 ...

  6. C#总结(六)EventBus事件总线的使用-自己实现事件总线

    在C#中,我们可以在一个类中定义自己的事件,而其他的类可以订阅该事件,当某些事情发生时,可以通知到该类.这对于桌面应用或者独立的windows服务来说是非常有用的.但对于一个web应用来说是有点问题的 ...

  7. Android 开发 框架系列 EventBus 事件总线

    介绍 GitHub:https://github.com/greenrobot/EventBus 先聊聊EventBus 线程总线是干什么的,使用环境,优点.缺点. 干什么的? 一句话,简单统一数据传 ...

  8. EventBus 事件总线之我的理解

    用例:假设公司发布了一个公告 需要通过短信 和 邮件分别2种方式 通知员工 1:首先我们建立领域模型 /// <summary> /// 领域核心基类 /// </summary&g ...

  9. Orchard EventBus 事件总线及 IEventHandler作用

    事件总线接口定义: public interface IEventBus : IDependency { IEnumerable Notify(string messageName, IDiction ...

随机推荐

  1. AtCoder Beginner Contest 139F Engines

    链接 problem 给出\(n\)个二元组\((x,y)\).最初位于原点\((0,0)\),每次可以从这\(n\)个二元组中挑出一个,然后将当前的坐标\((X,Y)\)变为\((X+x,Y+y)\ ...

  2. ThinkPHP 3.2 自定义基类 Model

    ThinkPHP 提供了一个 Model 类,供其他的 Model 进行继承.Model 类中是 MVC 中的模型类,它是调用 持久层 的上层类.感觉这么描述问题很多,但是有什么办法呢?但是,这个 M ...

  3. ThinkPHP框架获取上一条插入语句产生的id

    今天在fastAdmin框架想搞一个拖动进行排序的功能 遇到一个问题是权重的字段值一样的话拖动会出bug,所以想让权重字段(weigh)的值等于当前id的值, 搜索看到的方法如下 实际应用的地方,是写 ...

  4. 微软宣布.NET Native预览版 C#可编译为本地机器码【转】

    英文原文:Announcing .NET Native Preview 微软在 MSDN 博客上宣布了 .NET Native 的开发者预览版..NET Native 可以将 C# 代码编译成本地机器 ...

  5. Visual Studio 语法高亮插件推荐

    编辑器 GItHub:https://github.com/Art-Stea1th/Enhanced-Syntax-Highlighting Visual Studio Marketplace:htt ...

  6. 第三章 web设计原则:

    程序员的修炼从优秀带卓越 第三章 web设计原则:    网站的评判标准     加载的速度要快     这到底是什么东西     给我看一个例子     清清楚楚的告诉我要做什么,并且扫除障碍   ...

  7. dubbo(提供者、消费者)基于java的实现

    1.安装好jdk.zookeeper以后可以尝试开发代码进行dubbo的学习和练习. 首先创建Dubbo的Provider配置.创建一个maven project工程. RPC框架,不希望Consum ...

  8. 【机器学习笔记】来吧!解析k-NN

    序: 监督型学习与无监督学习,其最主要区别在于:已知的数据里面有没有标签(作为区别数据的内容). 监督学习大概是这个套路: 1.给定很多很多数据(假设2000个图片),并且给每个数据加上标签(与图片一 ...

  9. OWIN,Katana,identity整体概述

    在用asp.net identity的时候,发现很多概念不是很懂,特地去查资料了解了一些相关信息,现在做下笔记. 1.OWIN,OWIN是Open Web Server Interface for . ...

  10. vertx-mysql-client/java/

    Reactive MySQL Client是MySQL的客户端,它具有直接的API,专注于可伸缩性和低开销. 特征 事件驱动 轻巧的 内置连接池 准备查询缓存 游标支持 行流 RxJava 1和RxJ ...