Wiring up events from dll loaded at runtime?
Basically I want to be able to write a dll for my application that I will be able to put in a specific folder using a specific name and at runtime have that dll loaded and subscribe to a specific event. As an example I have a simple Windows Form App with a single button on it. I want to be able to have a MessageBox displayed when the button click event takes place but I want the displayed message to be controlled by an external dll that i开发者_Python百科s loaded at runtime. What would be the best way to accomplish this?
Create an interface that includes at least one method to handle the event (your application will have to reference the assembly in which this is defined):
public interface IEventHandler {
void HandleEvent(object sender, EventArgs e);
}
Add a class to the dll you want to load at runtime that implements the interface:
public class ConcreteEventHandler: IEventHandler {
public void HandleEvent(object sender, EventArgs e) {
// do something here
}
}
In your application, use reflection to load the dll and create an instance of your concrete handler (error checking omitted):
// The assembly name/location could be configurable
Assembly assembly = Assembly.Load("MyAssembly.dll");
// The type name could be configurable
Type type = assembly.GetType("ConcreteEventHandler");
IEventHandler handler = Activator.CreateInstance(type) as IEventHandler;
You can hook this handler up to whatever you want, e.g.:
MyButton.OnClick += handler.HandleEvent;
Is the DLL a single well-known one or will you be loading different or multiple ones? If the latter, I suggest looking into the AddIn
framework in .NET 3.5.
Given either of those choices, a very good design pattern to employ in this case is the Observer pattern. Your "observers" are watching the button click event (the observed) and execute their MessageBox
(es) appropriately.
精彩评论