Search code examples
c#reflectionactivatortypeloadexception

Activator.CreateInstance(string, string) throwing TypeLoadException


I have the following code:

public static void Invoke(string assemblyName, string scheduledTaskExecutorName)
{
    ObjectHandle objectHandle = Activator.CreateInstance(assemblyName, scheduledTaskExecutorName);
    IScheduledTaskExecutor scheduledTaskExecutor = (IScheduledTaskExecutor)objectHandle.Unwrap();
    scheduledTaskExecutor.ExecuteScheduledTask();
}

I have a class called DummyScheduledTaskExecutor which looks like this:

public class DummyScheduledTaskExecutor : IScheduledTaskExecutor
{
    public void ExecuteScheduledTask()
    {
        DummyTextFile.Text = "Success!";
    }
}

It resides in an assembly whose assembly name (as defined in the assembly's properties) is Tests.WebApplication.Application.Unit.

My call to Invoke(string, string) looks like this:

ScheduledTaskInvoker.Invoke("Tests.WebApplication.Application.Unit", "DummyScheduledTaskExecutor");

Trying to run this code just throws a TypeLoadException. Have I expressed the assembly or type name incorrectly, or is something else going on?


Solution

  • scheduledTaskExecutorName need to include the namespace.

    Try including the whole namespace in your second parameter.

    My example:

    namespace WindowsFormsApplication6
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
    
                object obj = Activator.CreateInstance(null, "WindowsFormsApplication6.TestClass");
            }
        }
    }
    
    namespace WindowsFormsApplication6
    {
        public class TestClass
        {
    
        }
    }