Clean architecture
AutomateIt's code is organised in layers that depend only inwards: the business rules know nothing about databases, web frameworks or hardware, so they can be tested on their own and outlive the technology around them. The rule is not a convention: tests check it on every build.
Dependencies point inwards only.
The layers
- Domain
- Entities, value objects and domain events, with no dependency at all: no framework, no database, no public setters. Invariants are checked where the data lives.
- Application
- One folder per use case area (access, actions, charging, programming, audit…). Each use case is a command or a query with its handler. The ports it needs (repositories, the unit of work, device gateways, the realtime push) are interfaces declared here and implemented outside.
- Infrastructure
- The adapters: persistence with EF Core and PostgreSQL, device gateways over Dapr, identity, realtime and background workers.
- Hosts
- The API is the composition root that wires everything together; the web host, the device services and a database tool are hosts of their own. Shared request and response types live in a separate Contracts project, so the screens never see domain types.
The dependency rule, tested
Architecture tests with ArchUnitNET load the compiled assemblies and fail the build as soon as a layer uses something it may not. A second set checks the project references themselves.
[Fact]
public void Domain_DependsOnNothingElseInTheSolution() =>
Types().That().Are(In(Domain)).Should()
.NotDependOnAnyTypesThat().Are(In(Application, Infrastructure, Contracts, Api, Web /* , every device service */))
.Check(Architecture);
[Fact]
public void Application_DoesNotUseInfrastructureFrameworks() =>
Types().That().Are(In(Application)).Should()
.NotDependOnAnyTypesThat().Are(Namespace("Microsoft.EntityFrameworkCore"))
.AndShould().NotDependOnAnyTypesThat().Are(Namespace("Microsoft.AspNetCore"))
.AndShould().NotDependOnAnyTypesThat().Are(Namespace("Dapr"))
.Check(Architecture);
Use cases: handlers and decorators
Commands and queries are plain records with a handler: no mediator library and no object mapper, so every call can be followed in the code. Cross-cutting concerns are decorators around the handler, always in the same order: validation → handler → transaction → domain events → event log → realtime push.
public sealed record SetDeviceModeCommand(string Source, string Mode) : ICommand<Result>;
internal sealed class SetDeviceModeHandler(
IDeviceGatewayRegistry gateways, IDeviceStatusRepository statuses, IAccessContext access)
: ICommandHandler<SetDeviceModeCommand, Result>
{
public async Task<Result> HandleAsync(SetDeviceModeCommand command, CancellationToken ct)
{
var caller = await access.RequireAsync(Screens.Administration, Operations.ManageDevices, ct);
if (caller.IsFailure) return caller.Error;
if (gateways.Find(command.Source) is not { } gateway)
return Error.NotFound("Device.NotFound", $"No device service '{command.Source}'.");
// … switch the service between its simulator and the real equipment …
var status = await statuses.GetAsync(command.Source, ct);
status.RequestMode(command.Mode); // a domain method; no SaveChanges here
return Result.Success();
}
}
Handlers never save anything themselves. The transaction decorator commits only a successful result, and the domain events are published after the commit, so side effects (the event log, a command to the hardware, a push to the screens) only ever see committed state.
internal sealed class TransactionCommandDecorator<TCommand, TResult>(
ICommandHandler<TCommand, TResult> inner, IUnitOfWork unitOfWork) : ICommandHandler<TCommand, TResult>
where TCommand : ICommand<TResult>
where TResult : Result
{
public async Task<TResult> HandleAsync(TCommand command, CancellationToken cancellationToken)
{
var result = await inner.HandleAsync(command, cancellationToken);
if (result.IsSuccess)
{
await unitOfWork.SaveChangesAsync(cancellationToken); // then the domain events are published
}
return result;
}
}
Errors are results
A use case returns a Result: success, or an error with a stable code (validation, not found,
conflict, forbidden). Exceptions are kept for the truly unexpected. The API maps each kind of error to its
HTTP status, and the screens translate the code into the user's language.
Device services: the same shape every time
Every device service has the same four parts: Api (its endpoints and subscriptions), Application (what it does), Protocol (how it speaks to the equipment) and Simulation (a simulator with the same interface). A new family of equipment starts from that template, and its simulator makes it testable before the hardware is connected.
The same layering in Swift
atHouse is a Swift 6 app with strict concurrency, built in SwiftUI with Apple frameworks only. Its code sits in a local Swift package with three modules:
- Domain: the house, rooms, readings and rules, in plain Swift.
- Data: the REST client, the SignalR client for live updates, sign-in and the Keychain.
- Presentation: SwiftUI views with
@Observableview models (MVVM).
Data and Presentation depend on Domain, never on each other; the app target is the composition root. The demo mode simply swaps every Data adapter for an in-memory house, which also drives the previews and the presentation tests.
Tests
- Domain and use cases: written test-first, as Given / When / Then specifications on in-memory fakes.
- Infrastructure: against a real PostgreSQL in a throw-away container (Testcontainers).
- API: HTTP, authorization and message subscriptions, end to end in memory.
- Web: Blazor components with bUnit.
- Behaviour: features in Gherkin (Reqnroll), readable by the people who use them.
- Architecture: the dependency rule above.
xUnit v3 throughout; the quality gate requires at least 80 % coverage on new code.
Back to AutomateIt & atHouse or the architecture. Want this approach for your own software? Contact ESO.