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.)
Candidate APIs in the framework:
AssemblyDependencyResolverin System.Runtime.Loader having a methodstring 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
Assemblyfrom anAssemblyName, which obviously requires loading the former from somewhere.The creators of that library have externalized this problem by requiring the programmer to provide a
MetadataLoadContextwith aMetadataAssemblyResolverdependency 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.How do other libraries outside the framework deal with assembly resolution?
Mono.Cecil models assembly resolution with its
IAssemblyResolverabstraction and has a base implementation in theBaseAssemblyResolverclass.Roslyn has a
MetadataReferenceResolverabstraction which is implemented in e.g. theRuntimeMetadataReferenceResolverclass.(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.)
Some platform-specific pointers
.NET Core: On .NET Core, both of the above libraries appear to rely on the
TRUSTED_PLATFORM_ASSEMBLIESdata property inAppContext, which is documented in "Write a custom .NET Core host to control the .NET runtime from your native code". There's also anAPP_PATHdata 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.