Is there any public API in the .NET Framework, in .NET Core, or in .NET Standard that can resolve a System.Reflection.AssemblyName
to a file path of the assembly file that would be loaded, without actually loading that assembly?
The best I've currently got is this:
string ResolveToPath(AssemblyName name) => Assembly.ReflectionOnlyLoad(name).Location;
But that still causes the assembly to be loaded (albeit only into the reflection-only context).
(Assume that I do not want to change the way how the runtime locates assemblies. I'm asking this for use in a library, where I am not free to inspect application configuration files, defining an AppDomain.AssemblyResolve
handler, etc.)
AssemblyDependencyResolver
in System.Runtime.Loader having a method string ResolveAssemblyToPath(AssemblyName assemblyName)
, which is currently only available on .NET Core.
System.Reflection.MetadataLoadContext (source on GitHub, package on nuget.org), which apparently faces the exact same problem: being able to retrieve an Assembly
from an AssemblyName
, which obviously requires loading the former from somewhere.
The creators of that library have externalized this problem by requiring the programmer to provide a MetadataLoadContext
with a MetadataAssemblyResolver
dependency that does that work for it.
While this library comes with a single concrete implementation (PathAssemblyResolver
), it does not provide an implementation that encapsulates the runtime's native assembly probing/resolution algorithm.
Mono.Cecil models assembly resolution with its IAssemblyResolver
abstraction and has a base implementation in the BaseAssemblyResolver
class.
Roslyn has a MetadataReferenceResolver
abstraction which is implemented in e.g. the RuntimeMetadataReferenceResolver
class.
(I found out about this via the blog post "Referencing system assemblies in Roslyn compilations" by Luís Gonçalves and this GitHub post by @tmat.)
.NET Core: On .NET Core, both of the above libraries appear to rely on the TRUSTED_PLATFORM_ASSEMBLIES
data property in AppContext
, which is documented in "Write a custom .NET Core host to control the .NET runtime from your native code". There's also an APP_PATH
data property that could be used for probing.
.NET Framework: The assembly resolution algorithm is described in "How the Runtime Locates Assemblies". I was hoping that the framework would expose that algorithm with an API (it doesn't), but at least the algorithm can be reproduced given this information.