如何将参数传递给通过Assembly.CreateInstance加载的C#插件?
时间:2020-03-06 14:43:58 来源:igfitidea点击:
我现在拥有的(成功加载了插件)是:
Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;
这仅适用于具有无参数构造函数的类。如何将参数传递给构造函数?
解决方案
我们可以使用Activator.CreateInstance
Activator.CreateInstance接受一个Type以及要传递给Types构造函数的任何内容。
http://msdn.microsoft.com/zh-CN/library/system.activator.createinstance.aspx
称呼
public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
反而。
MSDN文件
编辑:如果我们要对此表示反对,请深入了解为什么这种方法是错误的或者不是最佳方法。
你不能。而是使用Activator.CreateInstance,如下面的示例所示(请注意,客户端名称空间位于一个DLL中,而主机位于另一个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());
}
}
}
}
我们也不能使用Activator.CreateInstance,这可能会更好。请参阅下面的StackOverflow问题。
如何在Activator.CreateInstance中传递ctor args或者使用IL?

