Writing an Effective CLAUDE.md Guide for C#/.NET Projects

    This article explains how to build a CLAUDE.md specification file that constrains AI coding assistants to generate production-grade C#/.NET code. It presents 13 core rules across five areas: type safety and null handling, async and concurrency control, dependency injection and service lifetimes, database and ORM practices, and exception handling with logging. Each rule includes configuration or code examples and the reasoning behind it, helping developers turn AI output from merely runnable into reliable and maintainable. The conclusion frames these rules as guardrails for collaborating with AI.

    Introduction: When AI Assistants Meet Enterprise .NET Architecture

    Code generation tools powered by large language models (LLMs) have become standard equipment for improving development efficiency. Yet many developers discover that while getting AI to produce code that “runs” is easy, getting it to produce C#/.NET code that meets enterprise standards and holds up in production is far more difficult.

    When you tell an AI coding assistant to “add an endpoint that returns paginated orders for a customer,” the model quickly produces seemingly correct code. On closer review, though, that code may run fine on a developer machine and then fall apart once deployed to a high-concurrency pre-production environment: ignored nullable reference warnings, hidden async void deadlock traps, thread pool starvation caused by .Result, overly broad exception catches, and DbContext mistakenly injected into singleton services.

    The root cause is that LLM training data is full of “tutorial-level” or “toy-level” examples rather than strict production architecture constraints. To change this, we need to establish a mandatory “coding constitution” for AI through a configuration file in the project root (such as CLAUDE.md or a similar context instruction file).

    This article explores how to build a set of 13 core rules for C#/.NET that constrain AI behavior and move its output from “usable” toward “reliable and durable.”


    1. Type Safety and Null Handling: Eliminating Runtime Uncertainty

    C# is a statically typed language whose core strength is catching errors at compile time. However, with poor configuration, AI-generated code quickly degrades into the loose state of a dynamic language.

    1. Enforce Nullable Reference Types (NRTs) and Treat Warnings as Errors

    This is the first step in modern .NET development. In the project file (.csproj), nullable reference types must be explicitly enabled and warnings promoted to compile errors. This forces AI to clearly distinguish between “may be null” and “never null” references.

    Configuration example:

    1. <PropertyGroup>
    2. <Nullable>enable</Nullable>
    3. <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    4. <LangVersion>latest</LangVersion>
    5. </PropertyGroup>

    In-depth analysis: Without this configuration, AI tends to generate vague signatures like string name. At runtime, a caller may pass null, causing downstream logic to throw a NullReferenceException. Once enabled, the compiler forces AI to add ? before parameters (such as string? name) or add null checks in the logic. The instruction file must strictly forbid using ! (the null-forgiving operator) to suppress warnings, which is equivalent to fooling yourself.

    2. Prefer Record Types for Immutable Data Models

    AI defaults to generating mutable class types with public setters, which is a recipe for disaster in concurrent scenarios. For DTOs (data transfer objects), domain events, and models that only need value equality, record or record struct should be mandatory.

    Instruction rule:
    “All transport-layer objects (DTOs), message queue events, and API request/response models must be defined with record and marked sealed by default.”

    1. public sealed record OrderDto(
    2. Guid Id,
    3. Guid CustomerId,
    4. decimal Total,
    5. IReadOnlyList<OrderLineDto> Lines);

    Value: record provides value-based equality comparison and immutability, effectively preventing data races caused by AI-generated code modifying the same object’s state in multiple places.

    3. Strictly Limit the Mutability of Collection Properties

    When generating object initialization, AI often likes to use List<T> as a public property type, which breaks encapsulation.

    Rule: Collection return values in public APIs must use interfaces or read-only types such as IReadOnlyList<T>, IReadOnlyDictionary<TKey, TValue>, or IEnumerable<T>. Internal implementation may store List<T> in private fields, but what is exposed externally must be read-only.


    2. Async Programming and Concurrency Control: Avoiding Thread Pool Starvation

    In web frameworks like ASP.NET Core, synchronously blocking on async code is the most common cause of service collapse. AI often lacks an intuitive understanding of “thread pool starvation.”

    4. Absolutely No async void or .Result / .Wait()

    async void makes exceptions impossible to catch and can crash the process directly; .Result and .Wait() block the current thread and easily cause deadlocks in the ASP.NET Core request context.

    Instruction rule:
    “Except for event handlers, the async void keyword is strictly forbidden; calling .Result, .Wait(), or .GetAwaiter().GetResult() is strictly forbidden. All async calls must be propagated all the way up (async all the way).”
    AI constraint logic: When generating Controller or service-layer code, method signatures must return Task or Task<T> and use the await keyword.

    5. Explicitly Configure CancellationToken Propagation

    Long-running operations (such as database queries and external API calls) must support cancellation. AI-generated code frequently ignores this parameter.

    Rule: In all method signatures that accept async operations, the last parameter must be CancellationToken cancellationToken. For ASP.NET Core actions, the token must be obtained from HttpContext.RequestAborted and passed down.

    6. Use Task.Run Appropriately for CPU-Bound Work

    For IO-bound operations (such as file reads/writes and network requests), the libraries already provide async APIs and there is no need to wrap them in Task.Run. For CPU-bound computation, however, it must be explicitly offloaded to a background thread to avoid blocking the UI thread or the web server’s request-processing threads.

    Instruction: “Distinguish CPU-bound from IO-bound operations. Use await Task.Run(() => ...) only for synchronous CPU-intensive logic.”


    3. Dependency Injection and Service Lifetimes: Preventing Architecture Decay

    ASP.NET Core’s built-in DI container is powerful but easy to misuse. AI frequently injects transient or scoped services into singleton services, causing the architecture to collapse.

    7. Respect Service Lifetime Boundaries

    Rules:

    • Injecting a scoped service (such as DbContext) directly into a singleton service is strictly forbidden. This causes state to leak across requests.
    • If a background service genuinely needs database access, it must manually create a scope using IServiceScopeFactory or IServiceScope.

    8. Prefer the Strongly Typed Options Pattern

    AI tends to write magic strings like IConfiguration["ConnectionStrings:Default"] everywhere.

    Rule: Reading configuration must use the Options pattern (IOptions<T>, IOptionsSnapshot<T>, or IOptionsMonitor<T>).

    1. public class OrderServiceOptions
    2. {
    3. public const string SectionName = "OrderService";
    4. public int PageSize { get; set; } = 20;
    5. public TimeSpan CacheExpiration { get; set; } = TimeSpan.FromMinutes(5);
    6. }

    Then bind it at startup via services.Configure<OrderServiceOptions>(config.GetSection(OrderServiceOptions.SectionName)) and inject IOptions<OrderServiceOptions> in the constructor. This provides compile-time safety and also supports hot updates (with IOptionsMonitor).

    9. Avoid the Service Locator Pattern

    Retrieving dependencies inside methods via IServiceProvider.GetService<T>() is strictly forbidden. This is an anti-pattern that hides a class’s real dependencies and makes unit testing extremely difficult. Dependencies must be provided through constructor injection.


    4. Database Access and ORM Rules: Ensuring Data Consistency

    Regardless of the ORM framework used (such as EF Core or Dapper), AI-generated code often lacks consideration for the underlying execution plan.

    10. Using DbContext Correctly

    • Never use it in a singleton: DbContext is not thread-safe and maintains internal state tracking.
    • Concurrency: If a request needs to process multiple queries in parallel, a separate DbContext instance should be created for each parallel branch (via IDbContextFactory<TContext>).
    • Query splitting: For complex queries with multiple Include calls, AI often generates a single giant SQL. AI should be required to consider using AsSplitQuery() to avoid memory overflow caused by a Cartesian product explosion.

    11. Enforce Parameterized Queries

    While mainstream ORMs use parameterized queries by default, when dynamic SQL concatenation is involved (such as dynamic sorting or dynamic filtering), AI may generate code with SQL injection risk.

    Instruction: “Any scenario that directly manipulates DbConnection or concatenates SQL strings must use parameterized command objects; concatenating user input into strings is strictly forbidden.”


    5. Exception Handling and Logging: From “Swallowing Errors” to “Observability”

    12. No Generic Try/Catch (Exception)

    AI-generated code is often wrapped in try { ... } catch (Exception ex) { _logger.LogError(ex); }. This swallows the exception so upstream cannot perceive the failure, and it makes it hard to distinguish business exceptions from system faults.

    Rules:

    • Only catch specific exceptions you expect to handle (such as DbUpdateConcurrencyException).
    • If you catch an exception, either apply compensation logic (Retry/Circuit Breaker) or rethrow it.
    • For framework-level exceptions (such as ModelState validation failures), use middleware to handle them uniformly rather than writing try-catch in every action.

    13. Structured Logging and Sensitive Data Masking

    AI tends to log with string interpolation: $"Processing order {order.Id}". This makes logs hard to parse and may leak sensitive information.

    Rules:

    • Structured logging templates must be used: _logger.LogInformation("Processing order {OrderId} for customer {CustomerId}", order.Id, order.CustomerId);
    • Outputting sensitive fields such as passwords, credit card numbers, and tokens directly in logs is strictly forbidden. AI must be explicitly told which fields are sensitive and need masking.

    Conclusion: Building Guardrails for AI Collaboration

    Generative AI is not a black box that can fully replace an architect; it is more like a junior developer with broad knowledge but lacking engineering discipline. A CLAUDE.md or project-level AI instruction file built from the 13 rules above is essentially a set of guardrails for this “junior developer.”

    In practice on cloud platforms such as Baidu AI Cloud, deeply integrating AI with CI/CD pipelines and static code analysis tools can greatly improve delivery quality. By constraining AI’s behavioral boundaries, we not only raise the first-pass success rate of code but, more importantly, prevent low-level failures that erupt late at night in production and are hard to diagnose.

    The goal of letting AI write code is no longer to “quickly generate garbage,” but to let machines handle boilerplate so human developers can focus on higher-level architecture design and business logic innovation.