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 ​

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

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

Notes ​

  • The method must be static, parameterless, return void, be non-generic, not be in a generic type, and be internal or public
  • 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:
csharp
#if !NET5_0_OR_GREATER
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public sealed class ModuleInitializerAttribute : Attribute { }
}
#endif

More information ​

Powered by Intracia