我现在拥有的(成功加载插件)是这样的:
Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;
这只适用于具有不带参数的构造函数的类。如何将参数传递给构造函数?
你不能。而是使用激活器.CreateInstance http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx如下例所示(请注意,客户端命名空间位于一个 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());
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)