0

I have a winform application and a service DLL (C#), both in the same solution and namespace. I'm loading the DLL dynamically so I can update the DLL in the future. The main form invokes a method from the dynamically loaded DLL and passes itself(this) as a variable.

Code in Main Form:

namespace MyNamespace
{
    class Form1
    {
        int i = 5;
        // Code
        .....

        private void CallDllMethod()
        {
            try
            {
                Assembly assembly = Assembly.LoadFrom("DllName.dll");
                Type type = assembly.GetType("MyNamespace.Class2");

                object ClassObj = Activator.CreateInstance(type);
                type.InvokeMember("DoSomething", 
                                   BindingFlags.Default | BindingFlags.InvokeMethod, 
                                   null, 
                                   ClassObj, 
                                   new object[] { this });
            }
            catch (Exception){...}      
        }
    }
}

Code in DLL:

namespace MyNamespace
{
    public class Class2
    {
        public void DoSomething(Form1 obj)
        {
                    ...
        }
    }
}

It tells me that it doesn't know Form1 obj and I think i understand why.

How can I make the dll "know" the main form so it can interact with it's members and method?? Is there a better way to achieve this goal?

Thanks you

Yoram
  • 179
  • 1
  • 2
  • 9

1 Answers1

1

The Dll will need to have a reference to the exe's project (or a 3rd project that defines the base-class or interface) that both the exe and the dll reference) in order to get members at design time.

If you can't do that you are stuck using reflection to call members.

If you only need to access base Form members from the dll you can declare the argument as Form instead of Form1. This would let you call things like .Close.

Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76
  • I eventually referenced the exe's project as you suggested and it works. Out of curiosity, at first I did manage to use reflection (Before I reference the exe) and I called public methods in the Main Form using `type.GetMethod("funcName").Invoke(formObj, new object[] { });`, but I couldn't find a way to access public member and their inner values. Is there a way? – Yoram Jul 30 '13 at 07:03
  • 1
    You can access properties, fields, and methods using the appropriate versions of `Type.GetMember`, `Type.GetField`, `Type.GetConstructor`, etc... You can also get non-public methods (and call them externally) by passing in `BindingFlags` indicating what visibility level you want. – Bradley Uffner Jul 30 '13 at 12:52