Type to search pages and rules.

Browse pages

LS2004: Command Handler Writes Through a Document Session

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 aggregate. This page states what the rule reports, where the error sits, and how to reach stored data through a Domain repository.

Markdown

Reference#

What the Rule Enforces#

LS2004 enforces Stage aggregate writes through repositories (litespec/backend/dotnet/persistence#stage-aggregate-writes-through-repositories). It runs in Application, Infrastructure, and Worker. Its category is LiteSpec.Layers. Severity and enablement follow the Analyzers overview.

What the Rule Reports#

The rule reports a command handler, which is a class whose name ends in CommandHandler or that implements ICommandHandler, 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#

C#
internal sealed class PlaceOrderCommandHandler
{
    private readonly IDocumentSession _session = null!;
}

Passing Example#

C#
internal sealed class PlaceOrderCommandHandler(IOrderRepository orderRepository)
{
    public void Handle(PlaceOrderCommand command)
    {
        var order = Order.Create(command.Quantity);
        orderRepository.Store(order);
    }
}

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 or WebApi.