Ask Learn
Preview
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
ModuleInitializer
attribute should not be used in librariesProperty | Value |
---|---|
Rule ID | CA2255 |
Title | The ModuleInitializer attribute should not be used in libraries |
Category | Usage |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 9 | As warning |
Applying ModuleInitializerAttribute to a method within a Class Library.
Module initializers are intended to be used by application code to ensure an application's components are initialized before the application code begins executing. If library code declares a method with the ModuleInitializerAttribute, it can interfere with application initialization and also lead to limitations in that application's trimming abilities. Library code should therefore not utilize the ModuleInitializerAttribute attribute.
Instead of using methods marked with ModuleInitializerAttribute, the library should expose methods that can be used to initialize any components within the library and allow the application to invoke the method during application initialization.
It is safe to suppress warnings from this rule if a solution uses a Class Library for code factoring purposes, and the ModuleInitializerAttribute method is not part of a shared or distributed library or package.
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA2255
// The code that's violating the rule is on this line.
#pragma warning restore CA2255
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA2255.severity = none
To disable this entire category of rules, set the severity for the category to none
in the configuration file.
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Usage.severity = none
For more information, see How to suppress code analysis warnings.
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign in