vendredi 24 mars 2023

How can application use reflection to use other dll's method which reply on the third dll

This is the definition of the DemoImport.dll, which relies on the RestSharp NuGet.

using RestSharp;

namespace DemoImport;

public class ImportClass
{
    public void JustAMethod()
    {
        Console.WriteLine("Hello");
        var client = new RestClient();
    }
}

This is the definition of the DemoClient, which use reflection to use the method "JustAMethod":

using System.Reflection;

Assembly assembly = Assembly.LoadFile(Directory.GetCurrentDirectory() + "\\Demo.dll");
Type? type = assembly.GetType("DemoImport.ImportClass");
object intance = Activator.CreateInstance(type)!;
type.GetMethod("JustAMethod").Invoke(intance,Array.Empty<object>());

However, I get error:

Unhandled exception. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.IO.FileNotFoundException: Could not load file or assembly 'RestSharp, Version=109.0.1.0, Culture=neutral, PublicKeyToken=598062e77f915f75'. System cannot find the target file。
File name: 'RestSharp, Version=109.0.1.0, Culture=neutral, PublicKeyToken=598062e77f915f75'
   at DemoImport.ImportClass.JustAMethod()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at Program.<Main>$(String[] args) in F:\Program.cs:line 6




Aucun commentaire:

Enregistrer un commentaire