I try to use [ModuleInitializer] in .net5 code. My test assembly
namespace TestAssembly
{
public class Class1
{
[ModuleInitializer]
public static void Init()
{
Console.WriteLine("ModuleInitializer");
}
}
}
I need the Init() method to be called on the assembly loading. Loading code
byte[] rawAssembly = LoadFile("TestAssembly.dll");
Assembly.Load(rawAssembly);
But the initializer isn't called on loading. Also I tried
Assembly.LoadFrom("TestAssembly.dll");
Assembly.LoadFile("TestAssembly.dll");
AppDomain domain = AppDomain.CurrentDomain;
Assembly assembly = domain.Load(rawAssembly);
The initializer is called after
var t = Type.GetType("TestAssembly.Class1, TestAssembly", AssemblyResolver, TypeResolver, false, true);
var obj = Activator.CreateInstance(t);
i.e. on the first use of any type from assembly. Is this normal behavior? Can I achieve a call to the initializer without any additional code on assembly loading?
Here is an explanation on github
A module initializer is executed at, or sometime before, first access to any static field or first invocation of any method defined in the module.