jeudi 19 mai 2022

C# DoNET 5 link a library with Dynamic DLL

I face an issue when i try to use a function from a .NET C# library class link to another library class loaded by Reflection

Here the Application call :

       private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Call static
            var lib = new StaticLib.StaticClass();
            var a = lib.Test(1); // Works fine


            // Call dynamic
            var DLL = Assembly.LoadFile(Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + "DynamicLib.dll");

            var theType = DLL.GetType("DynamicLib.DynamicClass");
            var inst =  Activator.CreateInstance(theType);
            
            var method_1 = theType.GetMethod("GetInvert_1");
            var b = method_1.Invoke(inst, new object[] { 1 }); // Works fine
            
            var method_2 = theType.GetMethod("GetInvert_2");
            var c = method_2.Invoke(inst, new object[] { 1 }); // Exception
        }

The Dynamic library :

namespace DynamicLib
{
    public class DynamicClass
    {
        public static int GetInvert_1(int value)
        {
            return value * (-1);
        }

        public static int GetInvert_2(int value)
        {
            var lib = new StaticLib.StaticClass();
            return lib.Test(value);
        }
    }
}

The Static library used by the dynamic library :

namespace StaticLib
{
    public class StaticClass
    {
        public int Test(int value)
        {
            return value * (-1);
        }
    }
}
  • Tha call var lib = new StaticLib.StaticClass(); var a = lib.Test(1); : Works perfectly
  • The call var a = method_1.Invoke(c, new object[] { 1 }); works perfectly.
  • The call var b = method_2.Invoke(c, new object[] { 1 }); crashes at the right moment of Invoke. If i remove the call to StaticLibray.StaticClass.test, there is no problem.

Exception interne 1 : FileNotFoundException : Could not load file or assembly 'StaticLib, Version=1.0.0.0, >Culture=neutral, PublicKeyToken=null'. Le fichier spécifié est introuvable.

It makes me confused, because through the Dynamic library, i can not call the function Test. The file StaticLib.dll is in the same directory than the other files. If i remove the file StaticLib.dll, i can even not start the application. So the problem comes to the link between DynamicLib.dll and StaticLink.Dll

thank for help





Aucun commentaire:

Enregistrer un commentaire