Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribe to an event of a loaded assembly

I am trying to load an assembly during run-time and subscribe to its events. In my scenario the dll file has an ADD method that gets two integers as arguments and raises an event with a custom event argument that contains the sum.

Here is a part of my code to load 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 the event raised by the assembly. Any help would be appreciated.

Added: example DLL source

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; }
        }
    }
}
like image 871
Afshin Avatar asked Oct 21 '22 12:10

Afshin


1 Answers

Just take the ev1 you already have and call AddEventHandler like this:

ev1.AddEventHandler(obj, MyEventHandlerMethod);

however, you'll want to make sure you cleanup the handler by calling RemoveEventHandler so that garbage collection can occur.

ev1.RemoveEventHandler(obj, MyEventHandlerMethod);
like image 169
Mike Perrenoud Avatar answered Nov 04 '22 02:11

Mike Perrenoud