lundi 26 décembre 2022

.NET Reflection: Type is resolved from Assembly, but not from Module

I have the following code which loads an assembly via LoadFile and tries to get a generic type from it (.NET 6):

using System.Reflection;

var assemblyPath = "D:\\jb_lifetimes\\JetBrains.Lifetimes.dll";
var typeName = "JetBrains.Util.Util.StaticsForType`1[[JetBrains.Threading.ByteBufferAsyncProcessor," +
               " JetBrains.Lifetimes, Version=777.0.0.0, Culture=neutral, PublicKeyToken=3c74c1a6a8683340]]";
var moduleName = "D:\\jb_lifetimes\\JetBrains.Lifetimes.dll";

var assembly = Assembly.LoadFile(assemblyPath);
var fromAssembly = assembly.GetType(typeName);

Console.WriteLine($"Module count: {assembly.Modules.Count()}");

var module = assembly.GetModules().First(m => m.FullyQualifiedName == moduleName);
Console.WriteLine($"Resolved module: {module}");

Console.WriteLine($"Types count in module: {module.GetTypes().Length}");
Console.WriteLine($"Types count in assembly: {assembly.GetTypes().Length}");

var fromModule = module.GetType(typeName);

Console.WriteLine($"From assembly: {fromAssembly}");
Console.WriteLine($"From module: {fromModule}");

And get the following output:

Module count: 1
Resolved module: JetBrains.Lifetimes.dll
Types count in module: 316
Types count in assembly: 316
From assembly: JetBrains.Util.Util.StaticsForType`1[JetBrains.Threading.ByteBufferAsyncProcessor]
From module:

Type is resolved when it is acquired from Assembly.GetType, but Module.GetType returns null, however there is only one module in this assembly, and it is successfully resolved.

I don't understand why the type cannot be resolved from the only module of the assembly when it is successfully resolved from the assembly itself.

Some other observations:

  • If I replace LoadFile with LoadFrom, type is resolved from module as well. I know about different load contexts, but can't understand how they can affect the observed behavior
  • If I replace type name with JetBrains.Util.Util.StaticsForType1[JetBrains.Threading.ByteBufferAsyncProcessor], it is also resolved from module even with LoadFile




Aucun commentaire:

Enregistrer un commentaire