How to implement a program that analyze an assembly with AssemblyLoadContext

149 views Asked by At

I make test program to analyze information in assemblies using reflection.

Source code

using System.Reflection;
using System.Runtime.Loader;

var path = @"..\..\..\..\ClassLibrary1\bin\Debug\net8.0\ClassLibrary1.dll";
//var path = @"..\..\..\..\WebApplication1\bin\Debug\net8.0\WebApplication1.dll";
//var path = @"..\..\..\..\WpfApp1\bin\Debug\net8.0-windows\WpfApp1.dll";

var resolver = new AssemblyResolver(path);
var assembly = resolver.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(path)));

foreach (var type in assembly.GetTypes())
{
    System.Diagnostics.Debug.WriteLine(type.FullName);
}

public class AssemblyResolver : AssemblyLoadContext
{
    private AssemblyDependencyResolver resolver;

    public AssemblyResolver(string path)
    {
        resolver = new AssemblyDependencyResolver(path);
    }

    protected override Assembly? Load(AssemblyName assemblyName)
    {
        var assemblyPath = resolver.ResolveAssemblyToPath(assemblyName);
        return assemblyPath != null ? LoadFromAssemblyPath(assemblyPath) : null;
    }

    protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
    {
        var libraryPath = resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
        return libraryPath != null ? LoadUnmanagedDllFromPath(libraryPath) : IntPtr.Zero;
    }
}

Problem

The program works fine for class libraries.
However, for ASP.NET Core and WPF applications, Microsoft.AspNetCore.Mvc.Core and PresentationFramework cannot load the "System.Reflection.Re flectionTypeLoadException: 'Unable to load one or more of the requested types.'"

What I tried

Adding a FrameworkReference to the test program as follows will no longer cause an exception.

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
    <FrameworkReference Include="Microsoft.WindowsDesktop.App.WPF" />
  </ItemGroup>

However, this method cannot cope with unknown cases.

Question

How can we make it possible to load an assembly without adding a FrameworkReference to the test program?

0

There are 0 answers