Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

集合Autofac后ActionEventHandler如何触发? #4

Open
QQ897878763 opened this issue Jan 11, 2019 · 0 comments
Open

集合Autofac后ActionEventHandler如何触发? #4

QQ897878763 opened this issue Jan 11, 2019 · 0 comments

Comments

@QQ897878763
Copy link

圣杰兄请教一个问题下,我结合了Autofac实现了事件总线的注册和Trigger的解耦,但是唯独Action的注册和调用没法通过Autofac做到,后面尝试使用反射实现也没办法,原因是ActionEventHandler的构造函数就是一个Action,希望 圣杰兄帮忙指点下。这是我触发事件的那一段代码:

public void Trigger(TEventData eventData) where TEventData : IEventData
{
//从事件映射集合里获取匹配当前EventData(事件源数据)的Handler
List handlerTypes = _eventStore.GetHandlersForEvent(eventData.GetType()).ToList();
if (handlerTypes.Count <= 0) return;
//循环执行事件处理函数
foreach (var handlerType in handlerTypes)
{
var handlerInterface = handlerType.GetInterface("IEventHandler`1");
var eventHandler = ContainerManager.Current.Container.Resolve(handlerInterface);
if (eventHandler.GetType().FullName == handlerType.FullName)
{
var handler = eventHandler as IEventHandler;
handler?.HandleEvent(eventData);
}
else
{
//如果Ioc容器里没有则需要反射生成
//因为ActionEventHandler的构造函数需要有指定的入参:Action,这里没法反射!!
MethodInfo methodInfo = handlerType.GetMethod("HandleEvent").MakeGenericMethod();
if (methodInfo != null)
{
object obj = Activator.CreateInstance(handlerType);
methodInfo.Invoke(obj, new object[] { eventData });
}
}
}

    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant