Introduction
The ModuleInitializerAttribute in C# NET Core marks a method to run automatically when a module (assembly) loads, before any other code runs.
Module initializers are intended to be used by application code to ensure an application's components are initialized before the application code begins executing.
Applies to
| Product | Versions |
|---|---|
| .NET | 5, 6, 7, 8, 9, 10, 11 |
Key Rules
- A module cannot be deployed independently; instead, it is always part of an assembly.
- Must be static and return void (or async void).
- Must take no parameters.
- Must not be generic or inside a generic class.
- Must be internal or public.
Key Execution Rules
- No explicit ordering: The ModuleInitializerAttribute does not take a parameter, priority number, or sequence value to sort execution order.
- Compiler-dependent: The compiler decides the exact sequence, which can change between different project builds, updates, or toolchains.
- Module isolation: Best practices dictate that module initializers must be completely agnostic of one another and avoid dependencies on execution sequence.
Common Uses/Task
- Registering services or plugins.
- Setting up global configurations.
Console project example
In this example, there are two methods marked with [ModuleInitializer] whose code executes prior to the Program.Main.
- Sets the console window title
- Configure Serilog
- Reads settings from appsettings
- Validates that the expected connection string exists in appsettings.json
internal partial class Program
{
[ModuleInitializer]
public static void MainSetup()
{
var assembly = Assembly.GetEntryAssembly();
var product = assembly?.GetCustomAttribute<AssemblyProductAttribute>()?.Product;
Console.Title = product!;
WindowUtility.SetConsoleWindowPosition(WindowUtility.AnchorWindow.Center);
Setup();
}
private static void Setup()
{
SetupLogging.Development();
var services = ConfigureServices();
using var provider = services.BuildServiceProvider();
var setup = provider.GetService<SetupServices>();
setup!.GetConnectionStrings();
setup.GetEntitySettings();
SpectreConsoleHelpers.SetEncoding();
}
[ModuleInitializer]
public static void AppsettingsCheck()
{
if (!JsonHelpers.MainConnectionExists())
{
throw new MissingMainConnectionException();
}
}
}
ASP.NET Core project example
This example displays the current environment.
public class Helpers
{
[ModuleInitializer]
public static void Initialize()
{
SpectreConsoleHelpers.SetEncoding();
AnsiConsole.MarkupLine(":collision: [DeepPink1]Application is starting...[/]");
SpectreConsoleHelpers.PinkPill(Justify.Left,
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development"
? "Application is running in Development mode."
: "Application is running in Production mode.");
}
}

Top comments (0)