Loading assembly at runtime fails when I copy the DLL after program startup

▼魔方 西西 提交于 2019-12-05 03:46:04
Hans Passant

Feature, not a bug. It is a DLL Hell counter-measure. The operative term is 'loading context', search Suzanne Cook's blog for the phrase to learn more about it. In a nutshell, the CLR memorizes previous attempts to load an assembly. First and foremost, it records successful bindings and guarantees that the exact same assembly will be loaded again, even if the disk contents have changed. You can no doubt see the benefit of that, suddenly getting another assembly is almost always disastrous.

The same is true for failed assembly binds. It memorizes those as well, for much the same reason, it will fail them in the future. There is no documented way to reset the loading context that I know of. Assembly.LoadFile() loads assemblies without a loading context. But that causes a whole range of other problems, you really don't want to use it.

In order to bypass the CLR caching of LoadFrom attempts, you can change your code a little to use the Assembly.Load(byte[] rawAssembly) overload.

Something like this:

Assembly LoadWithoutCache(string path)
{
    using (var fs = new FileStream(path, FileMode.Open))
    {
        var rawAssembly = new byte[fs.Length];
        fs.Read(rawAssembly, 0, rawAssembly.Length);
        return Assembly.Load(rawAssembly);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!