Subscribe to the event of the loaded assembly

I am trying to load an assembly at runtime and subscribe to its events. In my dll script, the file has an ADD method that takes two integers as arguments and raises an event with a custom event argument containing the sum.

Here is the part of my code to download the dll file:

Assembly asm = Assembly.LoadFile(@"C:\Projects\Dll1.Dll");
Type typ = asm.GetType("DLL1.Class1", true, true);

var method = typ.GetMethod("add");
var obj = Activator.CreateInstance(typ);

EventInfo ev1 = typ.GetEvents()[0]; // just to check if I have the proper event
Type tDelegate = ev1.EventHandlerType; // just to check if I have the proper delegate

method.Invoke(obj, new object[] { 1, 0 });

But I have no idea how to subscribe to an event raised by the assembly. Any help would be appreciated.

Added: DLL source example

namespace Dll1
{
    public class Class1
    {
        int c = 0;

        public void add(int a, int b)
        {
            c =  a + b;
            if (Added !=null)
                Added(this, new AddArgs(c));
        }

        public delegate void AddHandler(object sender, AddArgs e);

        public event AddHandler Added;

    }

    public class AddArgs : EventArgs
    {
        private int intResult;

        public AddArgs(int _Value) 
        {
            intResult = _Value;
        }

        public int Result
        {
            get { return intResult; }
        }
    }
}
+5
source share
1 answer

Just take ev1which you already have and call it AddEventHandlerlike this:

ev1.AddEventHandler(obj, MyEventHandlerMethod);

however, you will want to make sure that you clear the handler by invoking RemoveEventHandlerso that garbage collection can occur.

ev1.RemoveEventHandler(obj, MyEventHandlerMethod);
+3

All Articles