Service layer (Fowler) vs application service vs domain service (Evans/DDD): responsibilities (orchestration, transactions, authorisation and mapping vs stateless domain logic spanning aggregates), what belongs in entities, how 'god' service layers create an anaemic domain model, thin controllers/minimal API endpoints, and a funds-transfer example in .NET 10.
These are three layers of responsibility:
order.Submit()), and they come first.When everything goes into a fat OrderService, entities become property bags: the anaemic domain model. Controllers should only translate HTTP. The trade-off is richer models and clear boundaries against more types and more thought about where each rule lives.
"The names get used loosely, so I separate them by what they're allowed to know. Fowler's service layer is the application's boundary: the set of operations the outside world can call, like 'place order' or 'transfer funds'. In DDD terms each of those is an application service, or in a vertical-slice codebase a command handler. It orchestrates: load the aggregates through repositories, check the user may do this, call the domain, save through the unit of work, publish an event, and return a result. It deals in DTOs, transactions and authorisation, but it shouldn't decide business outcomes.
Business outcomes belong in the domain. First choice is the entity or value object itself:
order.Submit()refuses an empty order, andMoney.Addrefuses mixed currencies. A domain service is for domain logic with no natural home on one object, usually because it involves several aggregates. Transferring money between twoAccounts is the classic example: debit one, credit the other, enforce the daily limit and the same-currency rule. AFundsTransferServiceis stateless, takes domain types, and has no idea that HTTP or EF Core exist. If it needs an exchange rate, it takes anIExchangeRateProviderinterface defined in the domain.The mistake I see is the fat service layer: an
OrderServicewith 3,000 lines that checks every rule, sets every property and callsSaveChanges, whileOrderis a bag of public setters. That's Fowler's anaemic domain model. The rules get duplicated in the next service that touches orders, and anyone can setStatus = Shippeddirectly. Controllers have a similar problem when they start validating business rules. My rule of thumb: controllers translate HTTP, application services orchestrate, entities enforce their own rules, and a domain service is the exception for logic that spans aggregates."
| Concern | Controller / endpoint | Application service / handler | Domain service | Entity / value object |
|---|---|---|---|---|
| HTTP binding, status codes | Yes | No | No | No |
| DTO mapping | Optional | Yes | No | No |
| Authorisation | Policy attribute | Resource checks | No | No |
Transaction / SaveChanges |
No | Yes | No | No |
| Business rule on one aggregate | No | No | No | Yes |
| Business rule across aggregates | No | No | Yes | Partly (each side's own rules) |
| Publishing events | No | Yes (or outbox) | No | Raises domain events |
| Smell | Fix |
|---|---|
| Entity with only public setters | Private setters + intention-revealing methods |
OrderService with every rule |
Move rules into Order; keep orchestration in the handler |
Domain service that calls DbContext |
Inject repositories into the application service instead |
| Controller checks "order must have lines" | Move to Order.Submit() |
Service named OrderManager/OrderHelper |
Name the use case or domain concept |
In a loyalty-points system, the "points can't go negative" rule lived in four services and was missing from a fifth (a batch import), which created about 1,200 negative balances in one month. Moving the rule into PointsAccount.Redeem() and making the setters private turned the bug into a compile error in the import and removed around 300 lines of duplicated checks.
Checks whether the candidate can place logic in the right layer and recognises the anaemic domain model as a consequence of fat services.
Green flags
Red flags
SaveChanges in domain services. HTTP request
|
Endpoint / controller (bind DTO, auth policy, map result -> 200/400/404)
|
Application service/handler (use case: load, authorise, call domain, save, publish)
| \
Repositories Domain service (stateless, spans aggregates)
| |
Aggregates <----------+ entities + value objects enforce their own invariants
|
Unit of work (DbContext.SaveChangesAsync)
One public method per use case (or one handler class per command). Typical steps:
It's thin by design: if it contains if (account.Balance < amount), a business rule has leaked.
Use one when the logic:
It should be pure where possible: domain types in, domain types (or domain events) out. It doesn't load or save; the application service does.
Fowler called it an anti-pattern in 2003: objects that look like domain objects but have no behaviour, with all logic in services. Costs:
It isn't always wrong: for CRUD with no rules, a transaction script or direct endpoint code is simpler. The problem is a complex domain modelled anaemically.
Minimal API endpoints or controllers should be a few lines: bind, call, map. Business validation ("an order needs a line") goes in the domain; input-shape validation (required fields, lengths) can stay at the edge. A useful check: could you call the use case from a message consumer without copying anything from the controller? If not, logic has leaked into it.
More types, and decisions about where each rule lives. The payoff grows with domain complexity and the number of entry points (API, consumer, batch job) that share the same rules.
Account with public setters and an AccountService; move the overdraft rule into Account.Withdraw and see which callers stop compiling.FundsTransferService and unit-test it with two in-memory accounts and no mocks.BackgroundService consumer.Service classes over 500 lines and list which methods contain business rules versus orchestration.Entities enforce their own rules, a domain service handles the cross-aggregate rule, and the application service orchestrates.
namespace Bank.Domain;
public readonly record struct Money(decimal Amount, string Currency)
{
public static Money operator -(Money a, Money b) => a.Currency == b.Currency
? new(a.Amount - b.Amount, a.Currency)
: throw new InvalidOperationException("Currency mismatch.");
public static Money operator +(Money a, Money b) => a.Currency == b.Currency
? new(a.Amount + b.Amount, a.Currency)
: throw new InvalidOperationException("Currency mismatch.");
}
public sealed class Account(Guid id, Guid ownerId, Money balance)
{
public Guid Id { get; } = id;
public Guid OwnerId { get; } = ownerId;
public Money Balance { get; private set; } = balance; // no public setter: rules can't be bypassed
public void Withdraw(Money amount)
{
if (amount.Amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
if ((Balance - amount).Amount < 0) throw new InvalidOperationException("Insufficient funds.");
Balance -= amount;
}
public void Deposit(Money amount)
{
if (amount.Amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
Balance += amount;
}
}
// Domain service: a rule that spans two aggregates, stateless, no EF Core or HTTP
public sealed class FundsTransferService
{
private const decimal DailyLimit = 10_000m;
public void Transfer(Account from, Account to, Money amount, decimal alreadyTransferredToday)
{
if (from.Id == to.Id) throw new InvalidOperationException("Cannot transfer to the same account.");
if (from.Balance.Currency != to.Balance.Currency) throw new InvalidOperationException("Accounts use different currencies.");
if (alreadyTransferredToday + amount.Amount > DailyLimit) throw new InvalidOperationException("Daily transfer limit exceeded.");
from.Withdraw(amount); // each entity still enforces its own invariants
to.Deposit(amount);
}
}
public interface IAccountRepository
{
Task<Account?> GetAsync(Guid id, CancellationToken ct);
Task<decimal> TransferredTodayAsync(Guid accountId, CancellationToken ct);
}
namespace Bank.Application;
using Bank.Domain;
public sealed record TransferRequest(Guid FromAccountId, Guid ToAccountId, decimal Amount, string Currency);
public sealed record TransferResult(decimal NewBalance);
public interface IUnitOfWork { Task<int> SaveChangesAsync(CancellationToken cancellationToken = default); }
// Application service: orchestration, authorisation and the transaction; no business rules
public sealed class TransferFundsHandler(IAccountRepository accounts, FundsTransferService transfers, IUnitOfWork unitOfWork)
{
public async Task<TransferResult> HandleAsync(TransferRequest request, Guid currentUserId, CancellationToken ct)
{
var from = await accounts.GetAsync(request.FromAccountId, ct) ?? throw new KeyNotFoundException("Source account not found.");
var to = await accounts.GetAsync(request.ToAccountId, ct) ?? throw new KeyNotFoundException("Target account not found.");
if (from.OwnerId != currentUserId) throw new UnauthorizedAccessException();
var today = await accounts.TransferredTodayAsync(from.Id, ct);
transfers.Transfer(from, to, new Money(request.Amount, request.Currency), today);
await unitOfWork.SaveChangesAsync(ct); // one commit for both accounts
return new TransferResult(from.Balance.Amount);
}
}
// Program.cs: the endpoint only translates HTTP
builder.Services.AddSingleton<FundsTransferService>(); // stateless
builder.Services.AddScoped<TransferFundsHandler>();
app.MapPost("/transfers", async (TransferRequest request, TransferFundsHandler handler, ClaimsPrincipal user, CancellationToken ct) =>
{
var userId = Guid.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier)!);
return Results.Ok(await handler.HandleAsync(request, userId, ct));
}).RequireAuthorization();
OrderService while entities only have public setters. Why it is wrong: That's an anaemic domain model; rules are duplicated and any caller can set invalid state. Instead: Move rules into entity methods and keep the service for orchestration.DbContext. Why it is wrong: It mixes persistence and transactions into the domain and makes it hard to test. Instead: The application service loads, calls the domain service, and commits.HttpContext into domain services. Why it is wrong: It couples the domain to the API contract and transport. Instead: Map to domain types in the application layer.OrderManager, OrderHelper or OrderProcessor. Why it is wrong: Vague names attract unrelated responsibilities until it's a god class. Instead: Name the use case (SubmitOrderHandler) or the domain concept (FundsTransferService).I treat "where does this rule live?" as a design review question, not a folder convention. Entities first, a domain service only when the rule genuinely spans aggregates, and application services kept thin enough that I could call them from an API, a queue consumer and a batch job without copying any logic.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Transaction script in the endpoint | CRUD, few rules | Duplication if rules grow | Rules shared by several entry points |
| Application service + rich entities | Most business services | More types, design discipline | Pure CRUD |
| Domain service | Rules across aggregates, independent policies | Another abstraction | Logic that belongs to one entity |
| Fat service layer + anaemic entities | Rarely by choice | Duplicated, bypassable rules | Complex domains |
A useful measure: how many places enforce a given rule? If the answer is more than one, the rule isn't in the domain yet.
In an anemic domain model, entities are property bags with public getters and setters, and all business rules live in service classes that read and set those properties. In a rich domain model, entities own their behaviour: state is private, changes happen through methods like order.Pay(amount) that enforce invariants, and services only orchestrate (load, call, save). Anemic models scatter and duplicate rules, let any code put objects into invalid states, and are hard to test without a database. They are acceptable for simple CRUD or reporting with few rules. Move towards a richer model incrementally: make setters private, move one rule at a time into the entity, protect collections, and use value objects, guided by where bugs actually occur.
Tell, Don't Ask means you tell an object what you want done, and the object decides how, using its own data. Instead of a service doing if (order.Status == Pending && !order.IsPaid) order.Status = Cancelled;, you call order.Cancel(), and the order enforces the rule. That keeps invariants in one place, removes duplicated checks across services and moves you from an anaemic model towards a rich one. It applies to behaviour; for reading data to display or report, querying is exactly right.
Facade puts a simple entry point in front of a complex subsystem, so clients make one call instead of coordinating many classes. The subsystem stays available for anyone who needs more control.
.NET examples: File.ReadAllTextAsync (hides FileStream, StreamReader and encoding detection), HttpClient (hides the handler pipeline), JsonSerializer and DbContext. In business code, a checkout facade or application service coordinates inventory, payment and shipping for one use case.
The difference from a god service is cohesion. A facade is thin orchestration for one client need, and it delegates the rules to the subsystems. A god service has dozens of unrelated methods, owns business logic and has a ten-dependency constructor. The trade-off is that facades tend to grow, so split them by use case.
A repository gives the domain a collection-like interface for one aggregate root: GetAsync(orderId), Add(order). The domain asks for orders; it doesn't know about SQL, DbContext or tables. That's different from a DAO/table gateway, which mirrors tables with CRUD per table.
In EF Core, DbContext already is a repository (DbSet<T>) and a unit of work (SaveChanges). So a generic IRepository<T> with GetAll(), Update() and Save() usually adds a layer with no behaviour, and makes things worse:
IQueryable<T> GetAll() leaks EF semantics to callers.Save() per repository breaks the unit of work.A good repository is narrow and aggregate-specific, takes a CancellationToken and never commits. The trade-off is an abstraction that protects the domain model, against a layer that only renames EF Core.
Last updated 18 Nov 2026.