Skip to content

Instantly share code, notes, and snippets.

@KirillOsenkov
Forked from davkean/AssemblyLoadFile.md
Created June 2, 2017 22:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KirillOsenkov/acbb84dbdfc43f5a07d1598a0949c73e to your computer and use it in GitHub Desktop.
Save KirillOsenkov/acbb84dbdfc43f5a07d1598a0949c73e to your computer and use it in GitHub Desktop.
Why Assembly.LoadFile is not the right API to call

Assembly.LoadFile is almost always the wrong API to call inside an application. It says to the CLR “hands off, this assembly will live in its own little universe and don’t you apply any of your normal rules for loading assemblies”. Below you’ve effectively loaded two of these universes and one doesn’t see the other. LoadFile also forces you to hook onto AssemblyResolve (like you’ve done below[1]) and tell the CLR about every dependency that assembly needs to resolve. It also opts you out of other things such as binding redirects, retargeting (v1 portable won’t load below) and a few other things.

Assembly.LoadFile is used by designers, and should be called Assembly.LoadFile_ForDesignerUseOnly, it’s unfortunate it has such as tempting name.

If this is inside of VS, it is most definitely not the correct API to call. You want to use Assembly.Load, Assembly.LoadFrom and/or use VS related APIs for registering binding paths. It already has an assembly resolve, and no one else should be hooking onto it.

[1] That below code has subtle bug, try do a LoadFrom on Microsoft.VisualStudio.CoreUtility.dll before calling LoadFile – now there’s two versions of it loaded, and you’ll return the wrong one from AssemblyResolve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment