vendredi 24 juillet 2020

Passing additional information to event handler in dynamic event hooking

I am trying to hook to an event dynamically using reflection. The code is successfully getting execution to handler function HandleInfoMessage. The issue I need to address, at times different events with same evernt args type raise events and from the event args I am not able to identify the name of the event particularly raised. Is there any way that I can get the event name in handling function when it get raised?

public void AsyncRegisterForEventInternal(string eventName, ToolComponent toolComponent) {
    EventInfo ev = toolComponent.GetType().GetEvent(eventName);
    var handler = Create(ev, HandleInfoMessage);
    ev.AddEventHandler(toolComponent, handler);
}

private Delegate Create(EventInfo evt, Action < object, EventArgs > d) {
    var handlerType = evt.EventHandlerType;
    var eventParams = handlerType.GetMethod("Invoke").GetParameters();
    var parameters = eventParams.Select(p = >Expression.Parameter(p.ParameterType, "x")).ToArray();
    var body = Expression.Call(Expression.Constant(d), d.GetType().GetMethod("Invoke"), parameters[0], parameters[1]);
    var lambda = Expression.Lambda(body, parameters.ToArray());
    return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);
}

protected virtual void HandleInfoMessage(object obj, EventArgs eventArgs) {
    Console.WriteLine("InfoMessage {0}:{1}", obj.GetType().ToString(), eventArgs.GetType().ToString());
}




Aucun commentaire:

Enregistrer un commentaire