如何将参数传递给通过Assembly.CreateInstance加载的C#插件?

e-h*_*der 5 c# arguments assemblies createinstance

我现在拥有的(成功加载插件)是这样的:

Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;
Run Code Online (Sandbox Code Playgroud)

这仅适用于具有不带参数的构造函数的类.如何将参数传递给构造函数?

Mag*_*oll 12

你不能.而是使用Activator.CreateInstance,如下面的示例所示(请注意,Client命名空间位于一个DLL中,而Host位于另一个DLL中.两者必须位于同一目录中才能使代码生效.)

但是,如果你想创建一个真正可插入的接口,我建议你使用一个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());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)