jeudi 6 avril 2023

Dynamic subscription to event at runtime

I have implemented a very simple example on how I would want to subscribe dynamically to external events and perform some specific logic when the event is raised:

public static class ConsoleHost
{
    // Hooks onto an external event to automatically output a simple message
    public static void RegisterHook<TEventArgs>(object obj, string eventName, string message)
        where TEventArgs : EventArgs
    {
        // Create Dynamic Method
        var dynMethod = CreateHandler<TEventArgs>(() =>
        {
            Write(message);
        });
        
        // Retreive Method
        var methodInfo = dynMethod.GetMethodInfo();

        // Retreive EventInfo
        var eventInfo = obj.GetType().GetEvent(eventName);

        // Build dynamic delegate
        var dynDelegate = Delegate.CreateDelegate(eventInfo.EventHandlerType, methodInfo); // <-- This fails cause of different signatures

        // Finally add EventHandler
        eventInfo.AddEventHandler(obj, dynDelegate);
    }

    // Generate Proxy EventHandler
    private static EventHandler<TEventArgs> CreateHandler<TEventArgs>(Action action)
        where TEventArgs : EventArgs
    {
        return (object? sender, TEventArgs e) => action();
    }

    // Simple Output to Console for Example Purposes
    public static void Write(string message)
    {
        Console.WriteLine(message);
    }
}

However I get an error stating, that my dynamic method has a different signature than expected. What am I missing?





Aucun commentaire:

Enregistrer un commentaire