Use string of class name to new a class

0

I want to use a class name sting to new a class

NameSpace is Mcs.ControlMaster

Class Name is HostTransportCommand

after check some posts here. I use Activator

var msg = Activator.CreateInstance(Type.GetType("Mcs.ControlMaster.HostTransportCommand", true));

got exception

System.TypeLoadException
  HResult=0x80131522
  Message=Could not load type 'Mcs.ControlMaster.HostTransportCommand' from assembly 'Mcs.ControlMaster.UT, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

OKAY, the execution assembly is Mcs.ControlMaster.UT now 。and this class is in Mcs.ControlMaster. then

string fileToLoad = @"Mcs.ControlMaster.exe";
AssemblyName assemblyName = AssemblyName.GetAssemblyName(fileToLoad);
// assemblyName={Mcs.ControlMaster, Version=3.0.19.320, Culture=neutral, PublicKeyToken=null}
AppDomain myDomain = AppDomain.CreateDomain("MyDomain");
//myDomain={System.Runtime.Remoting.Proxies.__TransparentProxy}
Assembly myAssembly = myDomain.Load(assemblyName);
//myAssembly={Mcs.ControlMaster, Version=3.0.19.320, Culture=neutral, PublicKeyToken=null}
var myFunc = myAssembly.CreateInstance("HostTransportCommand");
// myFunc = null

if use

Type.GetType("Mcs.ControlMaster.UT, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", true));

will get

System.IO.FileLoadException: "The given assembly name or codebase was invalid." 

definition of HostTransportCommand

namespace Mcs.ControlMaster
{
    public class HostTransportCommand : JsonMessage

and definition of JsonMessage

namespace Mcs.Message
{
  public class JsonMessage : IMcsMessage

namespace Mcs.Message
{
  public interface IMcsMessage

How to solve this issue?

c#
reflection
asked on Stack Overflow Apr 16, 2019 by Ken Chu • edited Aug 15, 2020 by marc_s

1 Answer

0

Source code demo in my Github (batressc)

I created 2 projects (.net framework class libraries) using your classes definitions: Mcs.ControllerMaster and Mcs.Message. I reference Mcs.ControllerMaster inside of third project Msc.WindowsConsole (Windows console application).

For testing purposes, I added 2 properties to HostTransportCommand:

public class HostTransportCommand : JsonMessage {
    public string PropertyOne { get; set; }
    public int PropertyTwo { get; set; }
}

Then, in Main method I follow this steps:

class Program {
    static void Main(string[] args) {
        // Getting current execution directory
        var currentExecutingPath = Assembly.GetExecutingAssembly().CodeBase;
        string dirtyDirectory = Path.GetDirectoryName(currentExecutingPath);
        string directory = dirtyDirectory.Replace(@"file:\", "");

        // Loading assembly in app context
        var externalAssembly = File.ReadAllBytes($"{directory}\\Mcs.ControlMaster.dll");
        AppDomain.CurrentDomain.Load(externalAssembly);

        // Now is loading. Creating an instance of class
        // The object type is "ObjectHandle"
        var hostTransportCommandInstance = Activator.CreateInstance("Mcs.ControlMaster", "Mcs.ControlMaster.HostTransportCommand");

        // Getting properties for validate instance creation
        // Using Unwrap() method we can access to true Type (HostTransportCommand)
        var hostTransportCommandType = hostTransportCommandInstance.Unwrap().GetType();
        var hostTransportCommandProperties = hostTransportCommandInstance.Unwrap().GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

        // Showing information about type HostTransportCommand
        Console.WriteLine($"The type from Mcs.ControllerMaster is {hostTransportCommandType}");
        Console.WriteLine("Showing public properties (they was added for testing purposed):");
        foreach (PropertyInfo property in hostTransportCommandProperties) {
            Console.WriteLine(property.Name);
        }
        Console.ReadKey();
    }
}
answered on Stack Overflow Apr 18, 2019 by batressc • edited Apr 18, 2019 by batressc

User contributions licensed under CC BY-SA 3.0