Are there reference implementations of hot-swapping in .NET?

前端 未结 1 1642
我寻月下人不归
我寻月下人不归 2021-02-06 11:00

I\'m looking for a good implementation of hot-swapping done in .NET. The things I need are:

  • Being able to deploy DLLs in a particular folder and have a running sys
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 11:30

    You can provide a custom event handler for AssemblyResolve by calling newAppDomain() below. Supply your directory so AppDomain looks there. When loading a Type, use function loadFromAppDomain() to return it. This should allow you to copy new dlls to C:\dlls at runtime and reload from there. (Forgive me, I translated this from my VB source to C# according to your tag.)

    String dllFolder = "C:\\dlls";
    
    public void newAppDomain()
    {
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(assemblyResolve);
    }
    
    private static Assembly assemblyResolve(Object sender, ResolveEventArgs args){
        String assemblyPath = Path.Combine(dllFolder, new AssemblyName(args.Name).Name + ".dll");
        if(!File.Exists(assemblyPath))
        {
            return null;
        }
        else
        {
            return Assembly.LoadFrom(assemblyPath);
        }
    }
    
    private Type loadFromAppDomain(String className)
    {
        Assembly[] asses = AppDomain.CurrentDomain.GetAssemblies();
        List types = new List();
        foreach(Assembly ass in asses)
        {
            Type t = ass.GetType(className);
            if(t != null) types.Add(t);
        }
        if(types.Count == 1)
            return types.First();
        else
            return null;
    }
    

    0 讨论(0)
提交回复
热议问题