Domanda

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

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top