David
David

Reputation: 16130

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?

Upvotes: 1

Views: 5068

Answers (3)

James
James

Reputation: 2911

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
    {

    }
}

Upvotes: 2

Russell McClure
Russell McClure

Reputation: 4861

CreateInstance will assume the assembly is already loaded. My guess is it actually isn't. You need to use CreateInstanceFrom instead.

EDIT: Well if you know the assembly is loaded, then it is most likely a problem with your parameters to CreateInstance. Use the fully qualified type name instead of the simple class name like you are now.

Upvotes: 0

Ventsyslav Raikov
Ventsyslav Raikov

Reputation: 7202

did you try the assembly binding log?

http://msdn.microsoft.com/en-us/library/e74a18c4.aspx

Upvotes: 0

Related Questions