views:

166

answers:

1

Hi,

I'm trying to load an assembly, instantiate a class from that assembly, and then call Run(), which should set a property inside this instance.

Loading the assembly seems to work fine as I'm able to list the types, but the called method seems to be ineffective: the property located in the new instance remains set to null, depsite the fact that it should be set to something.

I also tried calling the method using a type.InvokeMethod(...) syntax.

Method that loads the assembly, calls the constructor and calls the method:

private IEntryPoint ChargerAppli(AppInfo ai)
{
        string cheminAssemblies = "D:\\TFS\\OBL Microsoft\\Stages\\2010\\WPF\\Shell\\Shell\\Applications\\";

        Assembly a = Assembly.LoadFile(cheminAssemblies + ai.AssemblyName);
        Type type = a.GetType(ai.StartupClass);

        IEntryPoint instance = Activator.CreateInstance(type) as IEntryPoint;
        instance.Run();
        return instance;
}

IEntryPoint interface:

public interface IEntryPoint
{
    FrameworkElement HostVisual { get; set; }
    void Run();
}

IEntryPoint implementation that I'm trying to load, which is located in the new assembly:

class Bootstrap : IEntryPoint
{
    private FrameworkElement _visuel;

    public Bootstrap()
    {
        //do some work;
        this._visuel = new MainVisual();
    }

    public System.Windows.FrameworkElement HostVisual { get; set; }

    public void Run()
    {
        HostVisual = this._visuel;
    }
}

What may I be missing?

A: 

Hi, assuming the assembly is working, here is a simplified piece of code that I have used to accomplish the same task.

 Assembly assembly = Assembly.LoadFile(file);
 Type[] types = assembly.GetTypes();
 foreach (Type t in types)
 {
    MethodInfo[] methods = t.GetMethods();

   if (t.Name == "MyType")
   {
       foreach (MethodInfo method in methods)
       {
           if (method.Name == "Run")
           {
               try
               {
                   InterfaceToMyType activeModule = ("InterfaceToMyType")method.Invoke(null, args);
               }
               catch
               {
                    //do stuff here if needed
               }
           }
       }
   }
}
Brandi
It worked! Thanks a lot.The assembly is indeed working, and I also need to return the actual instance of the desired type, therefore I called Activator.CreateInstance() after I reach the desired type in the foreach.Thanks for your input, this has been of great help.
amazeas
Glad to have helped - many people on this community have helped me, so I try and be helpful when I can. :)
Brandi