c# - 如何在 C# 中动态加载父程序集中的引用

标签 c# .net-4.0

如何在 C# 中获取父程序集中的引用列表。我在想一个加载到另一个程序中的 DLL,驱动程序需要在反射和序列化中使用一些父程序集引用。到目前为止,我还没有尝试任何东西,因为我不确定从哪里开始。

最佳答案

这是一个非常经典的反射问题,当您需要加载一个程序集并且该程序集包含引用时,这些引用未引用到调用程序集。

基本上,您应该在单独的应用程序域中加载程序集。

例如,您有一个带有类 ProxyType 的项目 ProxyDomain:

public class ProxyType : MarshalByRefObject
{
    public void DoSomeStuff(string assemblyPath)
    {
        var someStuffAssembly = Assembly.LoadFrom(assemblyPath);

        //Do whatever you need with the loaded assembly, e.g.:
        var someStuffType = assembly.GetExportedTypes()
            .First(t => t.Name == "SomeStuffType");
        var someStuffObject = Activator.CreateInstance(someStuffType);

        someStuffType.GetMethod("SomeStuffMethod").Invoke(someStuffObject, null);
    }
}

并且在包含对 ProxyDomain 的引用的调用项目中,您需要加载程序集,执行 DoSomeStuff 并卸载程序集资源:

public class SomeStuffCaller
{
    public void CallDoSomeStuff(string assemblyPath)
    {
        AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
        //Path to the directory, containing the assembly
        setup.ApplicationBase = "...";
        //List of directories where your private references are located
        setup.PrivateBinPath = "...";
        setup.ShadowCopyFiles = "true";

        var reflectionDomain = AppDomain.CreateDomain("ProxyDomain", null, setup);

        //You should specify the ProxyDomain assembly full name
        //You can also utilize CreateInstanceFromAndUnwrap here:
        var proxyType = (ProxyType)reflectionDomain.CreateInstanceAndUnwrap(
            "ProxyDomain", 
            "ProxyType");

        proxyType.DoSomeStuff(assemblyPath);

        AppDomain.Unload(reflectionDomain);
    }
}

关于c# - 如何在 C# 中动态加载父程序集中的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15174884/

相关文章:

c# - 如何将 NInject 模块链接在一起

c# - 在 C# 中模拟打开 Excel

c# - 将约束类型传递给方法

c# - 想在 ASP.NET MVC 中每天执行一次查询

c# - Sendgrid 邮件功能在 .net Framework 4 中不起作用

c# - 如何使用 PCL 库中的 GZipStream?

c# - 使用正则表达式匹配连字符后的所有内容

c# - 将实体保存到数据库——我的 Save 方法应该返回保存的实体吗?

c# - 寻找 .NET 4 线程池

c# - 为什么 [Enum].Parse 有一个 ignoreCase 参数?