正确的方式来加载程序集,查找类并调用Run()方法 [英] Correct Way to Load Assembly, Find Class and Call Run() Method

查看:68
本文介绍了正确的方式来加载程序集,查找类并调用Run()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例控制台程序。

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类转换为某些东西吗?不知道一个程序集(动态代码)中的类型如何知道我的(静态程序集/ shell应用程序)中的类型。仅使用几行反射代码在一个对象上调用Run()更好吗?该代码应该是什么样的?

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?

更新:
William Edmondson-请参见注释

UPDATE: William Edmondson - see comment

推荐答案

使用AppDomain



将程序集加载到自己的 AppDomain 首先。

Use an AppDomain

It is safer and more flexible to load the assembly into its own AppDomain first.

所以不是先前给出的答案

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();

我建议以下内容(改编自相关问题的答案):

I would suggested the following (adapted from this answer to a related question):

var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

现在您可以卸载程序集并进行其他安全设置。

Now you can unload the assembly and have different security settings.

如果您想要更大的灵活性和功能来动态加载和卸载程序集,则应查看托管加载项框架(即 System .AddIn 命名空间)。有关更多信息,请参见 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.

这篇关于正确的方式来加载程序集,查找类并调用Run()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆