Are there reference implementations of hot-swappin

2019-03-16 12:21发布

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 system pick them up.
  • Having the running system update corresponding references in the container.

I've been looking into MEF and its directory loading mechanism, but it seems very unreliable. Maybe someone out there has an alternative implementation?

1条回答
仙女界的扛把子
2楼-- · 2019-03-16 12:53

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<Type> types = new List<Type>();
    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;
}
查看更多
登录 后发表回答