.net在运行时重新加载程序集

时间:2017-11-10 21:55:53

标签: c# .net unity3d .net-assembly

我搜索了很多关于在.NET中运行时重新加载程序集的信息。我能找到的唯一方法是使用另一个AppDomain。但这让事情变得非常复杂。在我的情况下几乎是不可能的,因为将在运行时加载的程序集中的类不会从MarshalByRefObject继承。我看过Unity游戏引擎。编辑器在运行时构建组件,只使用编译的程序集。怎么可能?

2 个答案:

答案 0 :(得分:4)

我是用MEF完成的。我不确定它是否适合您,但效果很好。然而,即使使用MEF,它也有些复杂。

在我的情况下,我正在从特定文件夹加载所有dll。

这些是设置类。

public static class SandBox
{
    public static AppDomain CreateSandboxDomain(string name, string path, SecurityZone zone)
    {
        string fullDirectory = Path.GetFullPath(path);
        string cachePath = Path.Combine(fullDirectory, "ShadowCopyCache");
        string pluginPath = Path.Combine(fullDirectory, "Plugins");

        if (!Directory.Exists(cachePath))
            Directory.CreateDirectory(cachePath);

        if (!Directory.Exists(pluginPath))
            Directory.CreateDirectory(pluginPath);


        AppDomainSetup setup = new AppDomainSetup
        {
            ApplicationBase = fullDirectory,
            CachePath = cachePath,
            ShadowCopyDirectories = pluginPath,
            ShadowCopyFiles = "true"
        };

        Evidence evidence = new Evidence();
        evidence.AddHostEvidence(new Zone(zone));
        PermissionSet permissions = SecurityManager.GetStandardSandbox(evidence);

        return AppDomain.CreateDomain(name, evidence, setup, permissions);
    }
}

public class Runner : MarshalByRefObject
{
    private CompositionContainer _container;
    private DirectoryCatalog _directoryCatalog;
    private readonly AggregateCatalog _catalog = new AggregateCatalog();


    public bool CanExport<T>()
    {
        T result = _container.GetExportedValueOrDefault<T>();
        return result != null;
    }

    public void Recompose()
    {
        _directoryCatalog.Refresh();
        _container.ComposeParts(_directoryCatalog.Parts);
    }

    public void RunAction(Action codeToExecute)
    {
        MefBase.Container = _container;
        codeToExecute.Invoke();
    }

    public void CreateMefContainer()
    {
        RegistrationBuilder regBuilder = new RegistrationBuilder();
        string pluginPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        _directoryCatalog = new DirectoryCatalog(pluginPath, regBuilder);
        _catalog.Catalogs.Add(_directoryCatalog);

        _container = new CompositionContainer(_catalog, true);
        _container.ComposeExportedValue(_container);
        Console.WriteLine("exports in AppDomain {0}", AppDomain.CurrentDomain.FriendlyName);
    }
}

这是实际的代码。

AppDomain domain = SandBox.CreateSandboxDomain($"Sandbox Domain_{currentCount}", directoryName, SecurityZone.MyComputer);
            foreach (FileInfo dll in currentDlls)
            {
                string path = Path.GetFullPath(Path.Combine(directoryName, dll.Name));
                if (!File.Exists(path))
                    File.Copy(dll.FullName, Path.Combine(directoryName, dll.Name), true);

                domain.Load(typeof(Runner).Assembly.FullName);
            }

您可以通过此操作恢复域名。

Runner runner = (Runner) domain.CreateInstanceAndUnwrap(typeof(Runner).Assembly.FullName, typeof(Runner).FullName);
runner.CreateMefContainer(); // or runner.Recompose();

您需要像这样调用您的代码。

runner.RunAction(() =>
                {
                    IRepository export = MefBase.Resolve<IRepository>();
                    export?.Get("123");
                    Console.WriteLine("Executing {0}", export);
                });

答案 1 :(得分:3)

一般来说,您不能在同一AppDomain中重新加载程序集。您可以动态创建一个并加载它(它将永远存在于您的AppDomain中),您可以加载另一个几乎但不完全相同的程序集副本,但是一旦程序集在AppDomain中,它就会#39 ;卡住了。

想象一下,库程序集定义了SomeType,而您的客户端代码只是创建了一个实例。如果卸载库,该实例应该发生什么?如果库位于另一个AppDomain中,则客户端将使用具有明确定义的(在MarshalByRefObject中)行为的代理(以使用域卸载zomby并在事先抛出异常)。支持卸载任意类型会使运行时非常复杂,不可预测或两者兼而有之。

至于Unity,请参阅this discussion。引用:

  

&#34;汇编装载&#34;听起来像某种快速更新检查,但实际上整个脚本环境重新加载。这将破坏管理土地上的一切。 Unity可以通过使用它的序列化系统从中恢复。 Unity在重新加载之前序列化整个场景,然后重新创建所有内容并反序列化whold场景。当然,只有可以序列化的东西才能生存下来。这个过程。