CA2255: The ModuleInitializer
attribute should not be used in libraries
Property | 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 8 | As warning |
Cause
Applying ModuleInitializerAttribute to a method within a Class Library.
Rule description
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.
How to fix violations
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.
When to suppress warnings
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.
Suppress a warning
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.