I have a C# .dll that is envoked from within a C# application useing “System.Reflection” at runtime. The .dll contains a WinForm class which is used to display information to the user. The .dll is envoked using the following code:
DLL = Assembly.LoadFrom(strDllPath);
classType = DLL.GetType(String.Format("{0}.{0}", strNsCn));
classInst = Activator.CreateInstance(classType, paramObj);
Form dllWinForm = (Form)classInst;
dllWinForm.ShowDialog();
Now, my problem is now that I want to return a string from the WinForm .dll. This could be an error or just to show that the process completed correctly. I know how this is done when calling a method from within a requested .dll, as follows:
System.Reflection.Assembly LoadedAssembly = System.Reflection.Assembly.Load("mscorlib.dll");
System.Console.WriteLine(LoadedAssembly.GetName());
object myObject = LoadedAssembly.CreateInstance("System.DateTime", false, BindingFlags.ExactBinding, null, new Object[] {2000, 1, 1, 12, 0, 0}, null, null);
MethodInfo m = LoadedAssembly.GetType("System.DateTime").GetMethod("ToLongDateString");
string result = (string) m.Invoke(myObject, null);
but how do you do this for my case of a WinForm called from a .dll at runtime?
Any suggestions would be most appreciated.
Okay, so to boil the question and the comments down, what we’re trying to do here is have a C# app that loads a dll that was implemented by a 3rd party at a later date, and the app needs to get some status information from the component in the loaded dll (the fact that the component uses WinForms vs. some other UI seems completely inconsequential).
The best way to do it is to start out with an interface or base class that can be shared between the hosting application and the loaded component. In order to achieve this, the interface needs to be in a separate dll. So first we create a class library project and add the following class:
Then add a reference to that class library from the project that implements the component you’re loading via reflection (or share it with your third party for them to implement). Here is an example implementation of Plugin Base:
And lastly the code to load and call the component:
He are some screenshots: