简体   繁体   中英

Way to embed/reference another DLL assembly while invoking a method using C# Reflection

Is there anyway to invoke methods using C# Reflection with embedded/reference dlls?

For example consider the following senario. I have a assembly call User.dll , which have the class as bellow

namespace User
{
    public class UserInfo
    {
        public static string Name = "Username";
    }
}

Using the above dll as reference, I can able to compile the following code and access UserInfo.Name variable.

using User;
using System.Windows.Forms;

public class Test
{
    public Test()
    {
        MessageBox.Show("Name : " + UserInfo.Name);
    }
}

Consider the above code is in another dll called Test.dll assembly. Using Assembly.LoadFile("Test.dll") and C# Reflection, when I try to invoke the Constructor, getting File not found runtime error.

Error

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: Could not load file or assembly 'DynamicAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. at Test..ctor() --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)

Assembly.LoadFile method only loads the specified file. You need to use Assembly.LoadFrom method in your case. Please check for differences between Assembly.LoadFile and Assembly.LoadFrom

LoadFrom() goes through Fusion and can be redirected to another assembly at a different path but with that same identity if one is already loaded in the LoadFrom context.

LoadFile() doesn't bind through Fusion at all - the loader just goes ahead and loads exactly* what the caller requested. It doesn't use either the Load or the LoadFrom context.

Your executing code sample would be like

    static void Main(string[] args)
    {
        var fileName = ""; //put here test.dll path
        Assembly ass = Assembly.LoadFrom(fileName);

        var type = ass.GetType("Test.Test"); 

        var test = Activator.CreateInstance(type);
    }

I had the same problem.

I just copied the DLL into bin folder of the project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM