# LS2004: Command Handler Writes Through a Document Session

## Intent

LS2004 is a compiler check that reports a command handler, the type that runs the state change, writing through a document session or database context instead of a repository, which bypasses the boundary that guards the business record. This page states what the rule reports, where the warning sits, and how to reach stored data through a Domain repository.

## Reference

### What the rule enforces

LS2004 enforces [Stage aggregate writes through repositories](https://litespec.dev/2.0.0/backend/dotnet/persistence.md#stage-aggregate-writes-through-repositories) (`litespec/backend/dotnet/persistence#stage-aggregate-writes-through-repositories`). It runs in Application and Infrastructure. Its category is `LiteSpec.Layers`. It reports a warning and is enabled by default, as the [Analyzers overview](https://litespec.dev/2.0.0/analyzers/README.md) describes.

### What the rule reports

The rule reports a command handler, recognized as in [LS2002: Command Handler Dispatches Another Command](https://litespec.dev/2.0.0/analyzers/rules/ls2002.md), that holds `IDocumentSession`, `DbContext`, or a `DbContext` subclass in a field, property, constructor parameter, or local, or that calls a member through such a receiver. In a declaration the diagnostic sits on the type. In a call it sits on the invoked member name.

### Failing example

```csharp
internal sealed class PlaceOrderCommandHandler
{
    private readonly IDocumentSession _session = null!;
}
```

### Passing example

```csharp
internal sealed class PlaceOrderCommandHandler(IOrderRepository orders)
{
    public void Handle(PlaceOrderCommand command) => orders.Store(command);
}
```

### How to fix

Reach persistence only through a Domain repository that the handler takes as a constructor parameter.

## Notes

### What the rule ignores

The rule does not report handlers that reach persistence only through a Domain repository, or query handlers. It does not run in Domain, Application.Abstractions, or WebApi.
