我现在拥有的(成功加载插件)是:
Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;
这仅适用于具有不带参数的构造函数的类。如何将参数传递给构造函数?
答案 0 :(得分: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());
}
}
}
}
答案 1 :(得分:3)
呼叫
public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
代替。 MSDN Docs
编辑:如果你要对此进行投票,请深入了解这种方法为什么是错误的,或者不是最好的方式。
答案 2 :(得分:2)
答案 3 :(得分:1)
Activator.CreateInstance接受一个Type以及你要传递给Types构造函数的任何内容。
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
答案 4 :(得分:0)
你也不能使用Activator.CreateInstance,它可以表现得更好。请参阅下面的StackOverflow问题。
How to pass ctor args in Activator.CreateInstance or use IL?