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

时光毁灭记忆、已成空白 提交于 2019-12-03 13:34:06

问题


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:


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;
}


来源:https://stackoverflow.com/questions/15232228/are-there-reference-implementations-of-hot-swapping-in-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!