Skip to content

Module initializers C# 9.0new scenarios

Run code in an assembly when it is first loaded.

Previously if an assembly (module) wished to perform initialization then it must be specifically called by the application or else the assembly author must resort to external tooling to inject a .NET module initializer.

Now with C# 9.0 developers can specify the ModuleInitializer attribute instead to have their assembly perform necessary initialization at load time.

Code

C#
class Profiler
{
    [ModuleInitializer]
    public static void Initialize()
    {
        SetupCollectors();
        WireUpEvents();
    }
}
C#
class Profiler
{
    public static void Initialize()
    {
        SetupCollectors();
        WireUpEvents();
    }
}

static void Main()
{
    Profiler.Initialize(); // Hope callers do this before using the profiler!
}

Notes

The ModuleInitializerAttribute is only available from .NET 5 onwards but creating your own with the same name is enough to make it work on earlier targets.

C#
#if !NET5
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public sealed class ModuleInitializerAttribute : Attribute { }
}
#endif

More information