Вопрос

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?

Это было полезно?

Решение

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
    {

    }
}

Другие советы

did you try the assembly binding log?

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

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top