C# - 正确的方式来加载大会,查找类并调用run()方法 [英] C# - Correct Way to Load Assembly, Find Class and Call Run() Method
问题描述
样品控制台程序。
class Program
{
static void Main(string[] args)
{
// ... code to build dll ... not written yet ...
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
// don't know what or how to cast here
// looking for a better way to do next 3 lines
IRunnable r = assembly.CreateInstance("TestRunner");
if (r == null) throw new Exception("broke");
r.Run();
}
}
我要动态地构建一个集(.dll),然后加载程序集,实例化一个类,并调用这个类的run()方法。我应该尝试铸造的TestRunner类的东西?不知道如何在一个组件(动态code)的种类会知道我种在我的(静态装配/外壳应用程序)。是更好地只使用反射code几行调用运行()只是一个对象?我应该是code样子?
I want to dynamically build an assembly (.dll), and then load the assembly, instantiate a class, and call the Run() method of that class. Should I try casting the TestRunner class to something? Not sure how the types in one assembly (dynamic code) would know about my types in my (static assembly / shell app). Is it better to just use a few lines of reflection code to call Run() on just an object? What should that code look like?
更新: 威廉·埃德蒙森 - 见注释
UPDATE: William Edmondson - see comment
推荐答案
这是更安全,更灵活的组件加载到自己的 AppDomain中
第一。
Use an AppDomain
It is safer and more flexible to load the assembly into its own AppDomain
first.
因此,而不是给出答案previously :
var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
我会建议如下(改编自这个回答一个相关的问题一>)
var domain = AppDomain.CreateDomain("NewDomainName");
var pathToDll = @"C:\myDll.dll";
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
现在,你可以卸载的组件,有不同的安全设置。
Now you can unload the assembly and have different security settings.
。欲了解更多信息,请参见本文的外接程序和扩展性上的MSDN 。
If you want even more flexibility and power for dynamic loading and unloading of assemblies you should look at the Managed Add-ins Framework (i.e. the System.AddIn
namespace). For more information see this article on Add-ins and Extensibility on MSDN.
这篇关于C# - 正确的方式来加载大会,查找类并调用run()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!