Search code examples
.netsystem.reflectionassembly-resolutionassembly-loading

How can I resolve an AssemblyName to an assembly file path without loading that assembly?


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.)


Solution

  • Candidate APIs in the framework:

    • 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.

    How do other libraries outside the framework deal with assembly resolution?

    Some platform-specific pointers