How to pass an argument to a C # plugin being loaded via Assembly.CreateInstance?

Now I have (which successfully loads the plug-in):

Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;

This only works for a class that has a constructor with no arguments. How to pass an argument to a constructor?

+5
source share
5 answers

You can not. Use Activator.CreateInstance instead , as shown in the example below (note that the client namespace is in one DLL and the node in another. Both must be found in the same directory for the code to work.)

, , Initialize, , , . , , , , "" , .

using System;
using Host;

namespace Client
{
    public class MyClass : IMyInterface
    {
        public int _id;
        public string _name;

        public MyClass(int id,
            string name)
        {
            _id = id;
            _name = name;
        }

        public string GetOutput()
        {
            return String.Format("{0} - {1}", _id, _name);
        }
    }
}


namespace Host
{
    public interface IMyInterface
    {
        string GetOutput();
    }
}


using System;
using System.Reflection;

namespace Host
{
    internal class Program
    {
        private static void Main()
        {
            //These two would be read in some configuration
            const string dllName = "Client.dll";
            const string className = "Client.MyClass";

            try
            {
                Assembly pluginAssembly = Assembly.LoadFrom(dllName);
                Type classType = pluginAssembly.GetType(className);

                var plugin = (IMyInterface) Activator.CreateInstance(classType,
                                                                     42, "Adams");

                if (plugin == null)
                    throw new ApplicationException("Plugin not correctly configured");

                Console.WriteLine(plugin.GetOutput());
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.ToString());
            }
        }
    }
}
+12

public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)

. MSDN

EDIT: , , , / .

+2

Activator.CreateInstance accepts the type and everything you want to pass to the type constructor.

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

+1
source

You also cannot use Activator.CreateInstance, which might work better. See StackOverflow question below.

How to pass ctor args to Activator.CreateInstance or use IL?

0
source

All Articles