Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Aug 19, 2025

Solution rebuilds were failing with System.TypeInitializationException errors for all analyzer classes as shown in the error screenshot. The issue occurred because static readonly DiagnosticDescriptor fields were immediately accessing Resources during type initialization, but the embedded resource file wasn't always available when MSBuild/Roslyn loaded the analyzer types during rebuild scenarios.

Root Cause

The analyzers used static readonly fields that eagerly accessed resources:

public static readonly DiagnosticDescriptor Rule = new(
    "CT0001",
    Resources.CT0001_Title,  // Resource access during static init
    Resources.CT0001_MessageFormat,
    "Style",
    DiagnosticSeverity.Error,
    isEnabledByDefault: true,
    description: Resources.CT0001_Description);

During rebuilds, this caused type initialization failures when the resource wasn't yet available.

Solution

Replaced eager static initialization with lazy initialization using Lazy<T>:

private static readonly Lazy<DiagnosticDescriptor> LazyRule = new(() => new DiagnosticDescriptor(
    "CT0001",
    Resources.CT0001_Title,
    Resources.CT0001_MessageFormat,
    "Style",
    DiagnosticSeverity.Error,
    isEnabledByDefault: true,
    description: Resources.CT0001_Description));

public static DiagnosticDescriptor Rule => LazyRule.Value;

This defers resource access until the rule is actually needed, preventing initialization exceptions during rebuilds while maintaining full API compatibility.

Changes Made

  • Updated BracesForControlFlowAnalyzer with lazy initialization
  • Updated EnumAssignmentAnalyzer with lazy initialization
  • Updated ObjectInitializationAnalyzer with lazy initialization
  • All existing functionality preserved - public API unchanged
  • Thread-safe lazy initialization ensures correct behavior in parallel builds

Testing

  • All 26 existing unit tests continue to pass
  • Multiple clean/rebuild cycles tested successfully
  • Parallel builds validated to work correctly

Fixes #7.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Co-authored-by: magesoe <8904582+magesoe@users.noreply.github.com>
Copilot AI changed the title [WIP] Error thrown when rebuilding projects Fix TypeInitializationException during solution rebuilds with lazy initialization Aug 19, 2025
Copilot AI requested a review from magesoe August 19, 2025 09:15
@magesoe magesoe marked this pull request as ready for review August 19, 2025 09:29
@magesoe magesoe merged commit 483a788 into master Aug 19, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Error thrown when rebuilding projects

2 participants