Designing Objects on ASP.NET Core
In this pack: sizing and rule strictness are set by the core
plugin's oo-design skill; each rule here keeps a core rule in this
language.
Overview
This skill holds only what ASP.NET Core changes on top of oo-csharp:
load that skill too, because its rules on records, nullable reference
types, structs, refusals and async still hold in an ASP.NET Core code
base. The framework supplies the container, the request pipeline and
EF Core; each of them offers a place to keep a decision that belongs to
the domain: a singleton that captures a scoped context, an entity whose
public setters hand its state to an endpoint, a bulk update that writes
behind the entity, several saves in one use case, and an endpoint or
middleware that grows the business logic. ASP.NET Core 10 and EF Core
10 on .NET 10 change where these rules are kept, not what they require.
When to use
- A service, hosted service, middleware or singleton takes a
DbContext or another scoped service.
- An entity has public setters, or its rules live in the endpoint that
loads and saves it.
- A concurrency token, a unique index or an optimistic concurrency
failure is being designed.
- A use case saves more than once, or a read tracks entities it never
changes.
- A value object is mapped as an owned entity type, or a complex type
is being weighed against one.
- A
MapPost endpoint or a middleware holds a rule, a chain of
checks, or a store call.
- A refusal from the domain reaches the caller as an HTML error page
rather than problem details.
When not to use
- The code is plain C# that uses no ASP.NET Core or EF Core type, which
oo-csharp covers.
- The question is how a Razor or Blazor component splits its state from
the domain: outside this skill, and
oo-separating-presentation-from-domain covers the core rule.
- A question no ASP.NET Core or EF Core feature changes, such as which
object owns a rule: the core skills, starting from
oo-design.
- The code is Java on Spring or Jakarta EE, which
oo-java-spring and
oo-java-jakarta-ee cover.
Core rules
Rule. Register each service with the lifetime of what it holds: a
DbContext, and every service that holds one, is scoped; no
singleton holds a scoped service; a hosted service creates a scope
for each unit of work through IServiceScopeFactory, as
oo-inverting-dependencies rules 2 and 3 and oo-taming-persistence
rule 4 ask. AddScoped registers a service for one request in MVC
or Razor Pages, or one circuit in Blazor, and AddDbContext
registers a context scoped by default. A service must not use a
context whose lifetime is shorter than its own. A singleton keeps a
scoped service for the life of the process, and a hosted service is
registered as a singleton: it cannot take a scoped service such as a
context in its constructor, and no scope is created for it by
default. Take IServiceScopeFactory instead, call CreateScope(),
resolve the scoped services from scope.ServiceProvider, and
dispose the scope with the unit of work.
A middleware that is not factory-based is activated once, so a scoped
service goes in Invoke or InvokeAsync, or the middleware is
factory-based. In the Development environment the default provider
performs scope checks for a scoped service resolved from the root
provider or injected into a singleton.
Default. Make Program.cs, or one registration method per module
that it calls, the composition root: each port is registered with
its adapter there, and no domain class receives IServiceProvider,
as oo-inverting-dependencies rules 3, 4 and 5 ask. The
application's services are registered on builder.Services where
the host is built, and each AddScoped<IPort, Adapter> call names
the port and the adapter together. A domain class takes its
collaborators through its constructor; it neither resolves a service
nor receives the container that could. A module may move its
registrations into one AddClinicModule method, but the method is
called from Program.cs and the root still reads as the object
graph.
The exception is a type the framework builds for a request without a
registration of its own, such as an MVC controller: ASP.NET Core
does not register controllers as services by default, the framework's
activator resolves their constructor parameters from the container,
and the root never constructs the controller. The controller names no
container.
Rule. Keep an entity's invariants under EF Core: private setters,
state changed only through methods named for domain actions that
check before they change anything, and a constructor that EF Core
binds by parameter name, as oo-encapsulating-state-and-behaviour
rules 1 and 2, oo-constructing-valid-objects rules 1 and 3, and
oo-working-within-a-framework rule 1 ask. EF Core calls the
constructor whose parameter names and types match mapped properties,
with camel-case parameters for Pascal-case properties, and it
accepts a constructor of any accessibility, though a lazy-loading
proxy needs it reachable from the proxy class. Properties without a
setter are not mapped by convention; EF Core treats a private setter
as read-write, so a private setter keeps the property mapped while
callers cannot assign it. The constructor sets each required field
and checks the values that arrive, and the entity's Offer, Send
or Record method reads the current state, refuses the call that
the rule forbids, and only then changes a field. A public setter
hands the same change to every caller, the endpoint included, with no
check at all.
When a property's accessor must not see the value EF Core writes,
configure a backing field in OnModelCreating; with a backing field
configured, EF Core reads and writes the field, not the property.
Rule. Give an entity that two requests can change at once a
concurrency token, or hold the rule it guards with a unique index,
both configured in the model (IsConcurrencyToken, IsRowVersion
or HasIndex in OnModelCreating) rather than by an attribute on
the domain type, and let the adapter turn the resulting
DbUpdateConcurrencyException or DbUpdateException into the
domain's refusal, as oo-working-within-a-framework rule 1,
oo-encapsulating-state-and-behaviour rule 1 and
oo-designing-failure-behaviour rule 7 ask. A concurrency token is
loaded with the entity and compared at SaveChangesAsync; when the
row changed since it was read, EF Core throws
DbUpdateConcurrencyException. Use IsConcurrencyToken for a token
the application assigns, and IsRowVersion for a provider-managed
row version where the provider has one. A unique index made with
HasIndex(...).IsUnique() holds a rule that no second row may
repeat, whatever code writes first, and a duplicate insert raises a
save error. EF Core reports a failed save as a DbUpdateException.
The model configuration stays in the adapter; an attribute such as
[Timestamp] or [ConcurrencyCheck] puts the store's marker on the
domain type. Catch the two store exceptions where the port is
implemented, and throw the refusal the domain already names, such as
WaitlistEntryAlreadyOffered, so the use case and the endpoint never
see the store's exception.
Rule. Treat one DbContext as one unit of work: the application
service loads, sends the commands and calls SaveChangesAsync once,
and a read that applies no rule uses AsNoTracking and projects to a
record, as oo-taming-persistence rules 4 and 6 and
oo-layering-the-system rule 6 ask. A context is designed for a
single unit of work and is not thread-safe. It loads the aggregate,
the entity's method changes it, and one SaveChangesAsync writes
every tracked change, inside the request's scope. A second save
splits one use case into two units: a failure after the first leaves
half the change stored, and the second load sees state the first
save already wrote. A read that decides nothing suits AsNoTracking
because it needs no change tracker and does no identity resolution;
add Select to return a record of the fields the caller reads, so no
entity outlives the query it came from.
Default. Map a value object as a complex type configured in the
model (ComplexProperty in OnModelCreating), with no EF attribute
on the value type, rather than as an owned entity type, as
oo-modeling-values-and-entities rules 2 and 3 and
oo-taming-persistence rule 2 ask. A complex type has no identity,
compares by value, and is the mapping EF Core describes for a value
object; it is not discovered by convention, so OnModelCreating
names each property that maps one. An owned entity type is still an
entity type behind the scenes: it has a hidden key and reference
semantics, so two equal values are not the same stored object, and a
value belongs in a complex type instead. In EF Core 10 a complex
property may be optional, hold a collection mapped with ToJson, or
be a struct or record struct; each is still a value with no
identity.
The exception is a value that the existing schema already maps as an
owned entity type in its own table: a complex type is stored in its
container's table or a JSON column and never in its own table, so
changing the mapping moves columns and rows. Keep the owned mapping
until a planned schema change, and map every new value as a complex
type.
Default. Keep endpoints and middleware at the edge: an endpoint
binds a request record, checks its shape, builds the domain's values
and calls the application service, and one IExceptionHandler turns
the domain's refusals into problem details, as
oo-placing-domain-logic rule 5, oo-crossing-system-boundaries
rules 1 and 2, and oo-designing-failure-behaviour rule 7 ask. A
minimal API route handler binds route values, a JSON body and the
services registered in the container; it turns the request record
into domain values through their constructors and leaves the
decision to the domain. A middleware reads the request or writes the
response and then calls the next middleware; a business condition
found there moves inward. One IExceptionHandler is registered with
AddExceptionHandler<T>(), called by UseExceptionHandler(), and
maps each refusal type to its status and problem details;
AddProblemDetails() registers the problem details service that
writes the body.
The exception is a read that decides no rule, such as a list of a
clinician's open appointments: the endpoint may call a query that
projects to a record and return it, and no domain object or
application service stands in the way.
Pattern
WaitlistEntry is a patient waiting for an appointment with a
clinician. Two entries for the same patient and clinician are two
entries, so it is an entity, and its status a rule guards: only a
waiting entry may be offered an appointment. The first version leaves
the status open to any caller and puts the check in the endpoint. The
second keeps the check in the entity and gives the endpoint one call to
make.
Before:
using Microsoft.EntityFrameworkCore;
public enum WaitlistStatus
{
Waiting,
Offered
}
public sealed class WaitlistEntry
{
public int Id { get; set; }
public string PatientId { get; set; } = "";
public string ClinicianId { get; set; } = "";
public WaitlistStatus Status { get; set; } = WaitlistStatus.Waiting;
public DateTime? OfferedAt { get; set; }
}
public sealed class WaitlistDb(DbContextOptions<WaitlistDb> options)
: DbContext(options)
{
public DbSet<WaitlistEntry> WaitlistEntries =>
Set<WaitlistEntry>();
}
public static class WaitlistEndpoints
{
public static void MapWaitlistEndpoints(this WebApplication app)
{
app.MapPost("/waitlist/{id:int}/offer",
async (int id, WaitlistDb db) =>
{
var entry = await db.WaitlistEntries.FindAsync(id);
if (entry is null)
{
return Results.NotFound();
}
if (entry.Status != WaitlistStatus.Waiting)
{
return Results.Conflict();
}
entry.Status = WaitlistStatus.Offered;
entry.OfferedAt = DateTime.UtcNow;
await db.SaveChangesAsync();
return Results.NoContent();
});
}
}
In the Before, WaitlistEntry has public setters, so every caller,
including the endpoint, can write Status and OfferedAt with no check
(rule 3). The endpoint reads Status, decides whether the offer is
allowed, and writes both fields, so the rule lives in the edge and a
second caller reaches the same state by a different path (rule 3). The
one SaveChangesAsync keeps the request to one unit of work, so rule 5
is not the defect here. The fence stores the waitlist row under its id
in the waitlist table, inside the request's scope, with that one call;
AddDbContext in Program.cs makes WaitlistDb scoped, and the fence
leaves that registration out.
After:
using Microsoft.EntityFrameworkCore;
public enum WaitlistStatus
{
Waiting,
Offered
}
public sealed class WaitlistEntry
{
public int Id { get; private set; }
public string PatientId { get; private set; } = "";
public string ClinicianId { get; private set; } = "";
public WaitlistStatus Status { get; private set; }
public DateTime? OfferedAt { get; private set; }
public WaitlistEntry(
int id, string patientId, string clinicianId)
{
if (string.IsNullOrWhiteSpace(patientId))
{
throw new ArgumentException(
"a waitlist entry names its patient",
nameof(patientId));
}
if (string.IsNullOrWhiteSpace(clinicianId))
{
throw new ArgumentException(
"a waitlist entry names its clinician",
nameof(clinicianId));
}
Id = id;
PatientId = patientId;
ClinicianId = clinicianId;
Status = WaitlistStatus.Waiting;
}
public void Offer(DateTime at)
{
if (Status != WaitlistStatus.Waiting)
{
throw new WaitlistEntryAlreadyOffered(Id);
}
Status = WaitlistStatus.Offered;
OfferedAt = at;
}
}
public sealed class WaitlistEntryAlreadyOffered(int id)
: InvalidOperationException(
$"waitlist entry {id} was already offered");
public sealed class WaitlistEntryNotFound(int id)
: InvalidOperationException($"no waitlist entry {id}");
public sealed class WaitlistDb(DbContextOptions<WaitlistDb> options)
: DbContext(options)
{
public DbSet<WaitlistEntry> WaitlistEntries =>
Set<WaitlistEntry>();
}
public sealed class OfferWaitlistEntry(WaitlistDb db, TimeProvider time)
{
public async Task OfferAsync(int waitlistEntryId)
{
var now = time.GetUtcNow().UtcDateTime;
var entry = await db.WaitlistEntries
.FindAsync(waitlistEntryId)
?? throw new WaitlistEntryNotFound(waitlistEntryId);
entry.Offer(now);
await db.SaveChangesAsync();
}
}
public static class WaitlistEndpoints
{
public static void MapWaitlistEndpoints(this WebApplication app)
{
app.MapPost("/waitlist/{id:int}/offer",
async (int id, OfferWaitlistEntry offer) =>
{
await offer.OfferAsync(id);
return Results.NoContent();
});
}
}
In the After, every property has a private setter and the constructor
sets the fields EF Core binds by name, so the entity is mapped and no
caller can assign a field (rule 3). Offer is the one method that
changes Status and OfferedAt; it checks the current status and
throws WaitlistEntryAlreadyOffered before it changes anything, so the
check sits in the entity rather than in one caller (rule 3). Two
requests that load the same waiting entry at once both pass Offer's
check and both save; the concurrency token rule 4 describes, left out
of this fence, is what refuses the second.
Program.cs registers WaitlistDb with AddDbContext and
OfferWaitlistEntry with AddScoped, both scoped, and registers
TimeProvider.System as a singleton. It registers one
IExceptionHandler with AddExceptionHandler<WaitlistExceptionHandler>(),
and calls UseExceptionHandler() and AddProblemDetails(); the fence
leaves those registrations and the handler out. The handler maps
WaitlistEntryNotFound to 404 and WaitlistEntryAlreadyOffered to
409, each with problem details, so neither refusal reaches the caller
as a 500 (rule 7). OfferWaitlistEntry asks the TimeProvider once
and passes that value to Offer, so the time comes from a collaborator
passed in rather than from a static call, which keeps
oo-designing-for-testability rule 5. It loads the entry, sends
Offer, and calls SaveChangesAsync once, so the use case is one unit
of work (rule 5).
The endpoint binds the route value and calls the application service;
it neither tests the status nor writes a field. The fence stores the
offered entry under its id in the waitlist table, inside the request's
scope, with the one SaveChangesAsync the application service calls.
The state keeps rules 3 and 5: the entity owns the check, and the use
case owns one save.
Red flags
Places to look, not verdicts. A red flag becomes a finding only with
evidence: a measurement, a reproducible bug, or a failing test.
- A singleton, a hosted service, a middleware constructor or a static
field that holds a
DbContext or another scoped service.
AddSingleton or AddTransient for a service that holds a
DbContext, or an AddDbContext overload that asks for a lifetime
longer than the request.
- An entity with a public setter, or a public parameterless
constructor added only for the store.
- An endpoint, a middleware or a controller that reads an entity's
state, decides, and then sets it.
- An
ExecuteUpdate or ExecuteUpdateAsync that writes a field a rule
guards, behind the entity's method.
- More than one
SaveChangesAsync in one use case, or a save in an
endpoint and another in the service it calls.
AsNoTracking on an entity the use case then changes.
- A value object mapped as an owned entity type, or a value type
carrying
[ComplexType], [Timestamp], [ConcurrencyCheck] or
another EF attribute.
- A rule that two requests can break with no concurrency token and no
unique index behind it.
- A domain refusal that reaches the caller as a 500 or an HTML error
page because no
IExceptionHandler maps it.
- An
IServiceProvider parameter in a domain class, or a service
resolved from HttpContext.RequestServices where a constructor
parameter was available.
Common mistakes
- Registering a service that holds a
DbContext as a singleton because
its own fields look stateless.
- Injecting a
DbContext into a hosted service's constructor, then
reusing that one context for every sweep.
- Adding a private parameterless constructor for EF Core instead of the
constructor it binds by parameter name.
- Making an entity's setters public "for EF Core" when a private setter
is mapped and keeps callers out.
- Calling
SaveChangesAsync after each change in a use case, so a
failure leaves the first change stored.
- Using
AsNoTracking and then changing the entity, expecting the next
save to write it.
- Mapping a value as an owned entity type and accepting its hidden key
and reference equality.
- Putting a concurrency token in an attribute on the domain type
rather than in
OnModelCreating.
- Catching
DbUpdateConcurrencyException in the endpoint and deciding
the domain's refusal there.
- Trusting a validation attribute or a request record to hold a rule
the domain must keep.
Related skills
oo-csharp holds the language rules this skill applies, including
its rules on records, nullable reference types and async.
oo-inverting-dependencies decides how collaborators reach an object
and where the composition root sits.
oo-taming-persistence sets the unit of work and keeps a mapping
decision in the adapter.
oo-encapsulating-state-and-behaviour keeps state behind methods
named for domain actions.
oo-constructing-valid-objects makes a constructor refuse broken
input.
oo-working-within-a-framework decides what a framework may shape and
what stays in the domain.
oo-designing-failure-behaviour names a refusal and translates an
outside failure where it crosses a boundary.
oo-layering-the-system keeps an endpoint and a store on their own
sides of the domain.
oo-modeling-values-and-entities decides value or entity and what
equality reads.
oo-placing-domain-logic keeps an application service to
coordination.
oo-crossing-system-boundaries gives each contract its own transfer
types.
oo-designing-aggregates decides what one transaction changes.
oo-designing-repositories declares a read and a repository in the
domain's words.
oo-separating-presentation-from-domain splits a screen's state from
the domain.
Further reading
1---2name: oo-csharp-aspnet3description: Use when ASP.NET Core code picks a scoped or singleton lifetime, tracks entities with EF Core, or keeps logic out of MapPost endpoints and middleware.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-csharp-aspnet7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Designing Objects on ASP.NET Core1213**In this pack:** sizing and rule strictness are set by the core14plugin's `oo-design` skill; each rule here keeps a core rule in this15language.1617## Overview1819This skill holds only what ASP.NET Core changes on top of `oo-csharp`:20load that skill too, because its rules on records, nullable reference21types, structs, refusals and async still hold in an ASP.NET Core code22base. The framework supplies the container, the request pipeline and23EF Core; each of them offers a place to keep a decision that belongs to24the domain: a singleton that captures a scoped context, an entity whose25public setters hand its state to an endpoint, a bulk update that writes26behind the entity, several saves in one use case, and an endpoint or27middleware that grows the business logic. ASP.NET Core 10 and EF Core2810 on .NET 10 change where these rules are kept, not what they require.2930## When to use3132- A service, hosted service, middleware or singleton takes a33 `DbContext` or another scoped service.34- An entity has public setters, or its rules live in the endpoint that35 loads and saves it.36- A concurrency token, a unique index or an optimistic concurrency37 failure is being designed.38- A use case saves more than once, or a read tracks entities it never39 changes.40- A value object is mapped as an owned entity type, or a complex type41 is being weighed against one.42- A `MapPost` endpoint or a middleware holds a rule, a chain of43 checks, or a store call.44- A refusal from the domain reaches the caller as an HTML error page45 rather than problem details.4647## When not to use4849- The code is plain C# that uses no ASP.NET Core or EF Core type, which50 `oo-csharp` covers.51- The question is how a Razor or Blazor component splits its state from52 the domain: outside this skill, and53 `oo-separating-presentation-from-domain` covers the core rule.54- A question no ASP.NET Core or EF Core feature changes, such as which55 object owns a rule: the core skills, starting from `oo-design`.56- The code is Java on Spring or Jakarta EE, which `oo-java-spring` and57 `oo-java-jakarta-ee` cover.5859## Core rules60611. Rule. **Register each service with the lifetime of what it holds: a62 `DbContext`, and every service that holds one, is scoped; no63 singleton holds a scoped service; a hosted service creates a scope64 for each unit of work through `IServiceScopeFactory`, as65 `oo-inverting-dependencies` rules 2 and 3 and `oo-taming-persistence`66 rule 4 ask.** `AddScoped` registers a service for one request in MVC67 or Razor Pages, or one circuit in Blazor, and `AddDbContext`68 registers a context scoped by default. A service must not use a69 context whose lifetime is shorter than its own. A singleton keeps a70 scoped service for the life of the process, and a hosted service is71 registered as a singleton: it cannot take a scoped service such as a72 context in its constructor, and no scope is created for it by73 default. Take `IServiceScopeFactory` instead, call `CreateScope()`,74 resolve the scoped services from `scope.ServiceProvider`, and75 dispose the scope with the unit of work.76 A middleware that is not factory-based is activated once, so a scoped77 service goes in `Invoke` or `InvokeAsync`, or the middleware is78 factory-based. In the Development environment the default provider79 performs scope checks for a scoped service resolved from the root80 provider or injected into a singleton.81822. Default. **Make `Program.cs`, or one registration method per module83 that it calls, the composition root: each port is registered with84 its adapter there, and no domain class receives `IServiceProvider`,85 as `oo-inverting-dependencies` rules 3, 4 and 5 ask.** The86 application's services are registered on `builder.Services` where87 the host is built, and each `AddScoped<IPort, Adapter>` call names88 the port and the adapter together. A domain class takes its89 collaborators through its constructor; it neither resolves a service90 nor receives the container that could. A module may move its91 registrations into one `AddClinicModule` method, but the method is92 called from `Program.cs` and the root still reads as the object93 graph.9495 The exception is a type the framework builds for a request without a96 registration of its own, such as an MVC controller: ASP.NET Core97 does not register controllers as services by default, the framework's98 activator resolves their constructor parameters from the container,99 and the root never constructs the controller. The controller names no100 container.1011023. Rule. **Keep an entity's invariants under EF Core: private setters,103 state changed only through methods named for domain actions that104 check before they change anything, and a constructor that EF Core105 binds by parameter name, as `oo-encapsulating-state-and-behaviour`106 rules 1 and 2, `oo-constructing-valid-objects` rules 1 and 3, and107 `oo-working-within-a-framework` rule 1 ask.** EF Core calls the108 constructor whose parameter names and types match mapped properties,109 with camel-case parameters for Pascal-case properties, and it110 accepts a constructor of any accessibility, though a lazy-loading111 proxy needs it reachable from the proxy class. Properties without a112 setter are not mapped by convention; EF Core treats a private setter113 as read-write, so a private setter keeps the property mapped while114 callers cannot assign it. The constructor sets each required field115 and checks the values that arrive, and the entity's `Offer`, `Send`116 or `Record` method reads the current state, refuses the call that117 the rule forbids, and only then changes a field. A public setter118 hands the same change to every caller, the endpoint included, with no119 check at all.120121 When a property's accessor must not see the value EF Core writes,122 configure a backing field in `OnModelCreating`; with a backing field123 configured, EF Core reads and writes the field, not the property.1241254. Rule. **Give an entity that two requests can change at once a126 concurrency token, or hold the rule it guards with a unique index,127 both configured in the model (`IsConcurrencyToken`, `IsRowVersion`128 or `HasIndex` in `OnModelCreating`) rather than by an attribute on129 the domain type, and let the adapter turn the resulting130 `DbUpdateConcurrencyException` or `DbUpdateException` into the131 domain's refusal, as `oo-working-within-a-framework` rule 1,132 `oo-encapsulating-state-and-behaviour` rule 1 and133 `oo-designing-failure-behaviour` rule 7 ask.** A concurrency token is134 loaded with the entity and compared at `SaveChangesAsync`; when the135 row changed since it was read, EF Core throws136 `DbUpdateConcurrencyException`. Use `IsConcurrencyToken` for a token137 the application assigns, and `IsRowVersion` for a provider-managed138 row version where the provider has one. A unique index made with139 `HasIndex(...).IsUnique()` holds a rule that no second row may140 repeat, whatever code writes first, and a duplicate insert raises a141 save error. EF Core reports a failed save as a `DbUpdateException`.142 The model configuration stays in the adapter; an attribute such as143 `[Timestamp]` or `[ConcurrencyCheck]` puts the store's marker on the144 domain type. Catch the two store exceptions where the port is145 implemented, and throw the refusal the domain already names, such as146 `WaitlistEntryAlreadyOffered`, so the use case and the endpoint never147 see the store's exception.1481495. Rule. **Treat one `DbContext` as one unit of work: the application150 service loads, sends the commands and calls `SaveChangesAsync` once,151 and a read that applies no rule uses `AsNoTracking` and projects to a152 record, as `oo-taming-persistence` rules 4 and 6 and153 `oo-layering-the-system` rule 6 ask.** A context is designed for a154 single unit of work and is not thread-safe. It loads the aggregate,155 the entity's method changes it, and one `SaveChangesAsync` writes156 every tracked change, inside the request's scope. A second save157 splits one use case into two units: a failure after the first leaves158 half the change stored, and the second load sees state the first159 save already wrote. A read that decides nothing suits `AsNoTracking`160 because it needs no change tracker and does no identity resolution;161 add `Select` to return a record of the fields the caller reads, so no162 entity outlives the query it came from.1631646. Default. **Map a value object as a complex type configured in the165 model (`ComplexProperty` in `OnModelCreating`), with no EF attribute166 on the value type, rather than as an owned entity type, as167 `oo-modeling-values-and-entities` rules 2 and 3 and168 `oo-taming-persistence` rule 2 ask.** A complex type has no identity,169 compares by value, and is the mapping EF Core describes for a value170 object; it is not discovered by convention, so `OnModelCreating`171 names each property that maps one. An owned entity type is still an172 entity type behind the scenes: it has a hidden key and reference173 semantics, so two equal values are not the same stored object, and a174 value belongs in a complex type instead. In EF Core 10 a complex175 property may be optional, hold a collection mapped with `ToJson`, or176 be a `struct` or `record struct`; each is still a value with no177 identity.178179 The exception is a value that the existing schema already maps as an180 owned entity type in its own table: a complex type is stored in its181 container's table or a JSON column and never in its own table, so182 changing the mapping moves columns and rows. Keep the owned mapping183 until a planned schema change, and map every new value as a complex184 type.1851867. Default. **Keep endpoints and middleware at the edge: an endpoint187 binds a request record, checks its shape, builds the domain's values188 and calls the application service, and one `IExceptionHandler` turns189 the domain's refusals into problem details, as190 `oo-placing-domain-logic` rule 5, `oo-crossing-system-boundaries`191 rules 1 and 2, and `oo-designing-failure-behaviour` rule 7 ask.** A192 minimal API route handler binds route values, a JSON body and the193 services registered in the container; it turns the request record194 into domain values through their constructors and leaves the195 decision to the domain. A middleware reads the request or writes the196 response and then calls the next middleware; a business condition197 found there moves inward. One `IExceptionHandler` is registered with198 `AddExceptionHandler<T>()`, called by `UseExceptionHandler()`, and199 maps each refusal type to its status and problem details;200 `AddProblemDetails()` registers the problem details service that201 writes the body.202203 The exception is a read that decides no rule, such as a list of a204 clinician's open appointments: the endpoint may call a query that205 projects to a record and return it, and no domain object or206 application service stands in the way.207208## Pattern209210`WaitlistEntry` is a patient waiting for an appointment with a211clinician. Two entries for the same patient and clinician are two212entries, so it is an entity, and its status a rule guards: only a213waiting entry may be offered an appointment. The first version leaves214the status open to any caller and puts the check in the endpoint. The215second keeps the check in the entity and gives the endpoint one call to216make.217218Before:219220```csharp221using Microsoft.EntityFrameworkCore;222223public enum WaitlistStatus224{225 Waiting,226 Offered227}228229public sealed class WaitlistEntry230{231 public int Id { get; set; }232 public string PatientId { get; set; } = "";233 public string ClinicianId { get; set; } = "";234 public WaitlistStatus Status { get; set; } = WaitlistStatus.Waiting;235 public DateTime? OfferedAt { get; set; }236}237238public sealed class WaitlistDb(DbContextOptions<WaitlistDb> options)239 : DbContext(options)240{241 public DbSet<WaitlistEntry> WaitlistEntries =>242 Set<WaitlistEntry>();243}244245public static class WaitlistEndpoints246{247 public static void MapWaitlistEndpoints(this WebApplication app)248 {249 app.MapPost("/waitlist/{id:int}/offer",250 async (int id, WaitlistDb db) =>251 {252 var entry = await db.WaitlistEntries.FindAsync(id);253 if (entry is null)254 {255 return Results.NotFound();256 }257 if (entry.Status != WaitlistStatus.Waiting)258 {259 return Results.Conflict();260 }261 entry.Status = WaitlistStatus.Offered;262 entry.OfferedAt = DateTime.UtcNow;263 await db.SaveChangesAsync();264 return Results.NoContent();265 });266 }267}268```269270In the Before, `WaitlistEntry` has public setters, so every caller,271including the endpoint, can write `Status` and `OfferedAt` with no check272(rule 3). The endpoint reads `Status`, decides whether the offer is273allowed, and writes both fields, so the rule lives in the edge and a274second caller reaches the same state by a different path (rule 3). The275one `SaveChangesAsync` keeps the request to one unit of work, so rule 5276is not the defect here. The fence stores the waitlist row under its id277in the waitlist table, inside the request's scope, with that one call;278`AddDbContext` in `Program.cs` makes `WaitlistDb` scoped, and the fence279leaves that registration out.280281After:282283```csharp284using Microsoft.EntityFrameworkCore;285286public enum WaitlistStatus287{288 Waiting,289 Offered290}291292public sealed class WaitlistEntry293{294 public int Id { get; private set; }295 public string PatientId { get; private set; } = "";296 public string ClinicianId { get; private set; } = "";297 public WaitlistStatus Status { get; private set; }298 public DateTime? OfferedAt { get; private set; }299300 public WaitlistEntry(301 int id, string patientId, string clinicianId)302 {303 if (string.IsNullOrWhiteSpace(patientId))304 {305 throw new ArgumentException(306 "a waitlist entry names its patient",307 nameof(patientId));308 }309 if (string.IsNullOrWhiteSpace(clinicianId))310 {311 throw new ArgumentException(312 "a waitlist entry names its clinician",313 nameof(clinicianId));314 }315 Id = id;316 PatientId = patientId;317 ClinicianId = clinicianId;318 Status = WaitlistStatus.Waiting;319 }320321 public void Offer(DateTime at)322 {323 if (Status != WaitlistStatus.Waiting)324 {325 throw new WaitlistEntryAlreadyOffered(Id);326 }327 Status = WaitlistStatus.Offered;328 OfferedAt = at;329 }330}331332public sealed class WaitlistEntryAlreadyOffered(int id)333 : InvalidOperationException(334 $"waitlist entry {id} was already offered");335336public sealed class WaitlistEntryNotFound(int id)337 : InvalidOperationException($"no waitlist entry {id}");338339public sealed class WaitlistDb(DbContextOptions<WaitlistDb> options)340 : DbContext(options)341{342 public DbSet<WaitlistEntry> WaitlistEntries =>343 Set<WaitlistEntry>();344}345346public sealed class OfferWaitlistEntry(WaitlistDb db, TimeProvider time)347{348 public async Task OfferAsync(int waitlistEntryId)349 {350 var now = time.GetUtcNow().UtcDateTime;351 var entry = await db.WaitlistEntries352 .FindAsync(waitlistEntryId)353 ?? throw new WaitlistEntryNotFound(waitlistEntryId);354 entry.Offer(now);355 await db.SaveChangesAsync();356 }357}358359public static class WaitlistEndpoints360{361 public static void MapWaitlistEndpoints(this WebApplication app)362 {363 app.MapPost("/waitlist/{id:int}/offer",364 async (int id, OfferWaitlistEntry offer) =>365 {366 await offer.OfferAsync(id);367 return Results.NoContent();368 });369 }370}371```372373In the After, every property has a private setter and the constructor374sets the fields EF Core binds by name, so the entity is mapped and no375caller can assign a field (rule 3). `Offer` is the one method that376changes `Status` and `OfferedAt`; it checks the current status and377throws `WaitlistEntryAlreadyOffered` before it changes anything, so the378check sits in the entity rather than in one caller (rule 3). Two379requests that load the same waiting entry at once both pass `Offer`'s380check and both save; the concurrency token rule 4 describes, left out381of this fence, is what refuses the second.382`Program.cs` registers `WaitlistDb` with `AddDbContext` and383`OfferWaitlistEntry` with `AddScoped`, both scoped, and registers384`TimeProvider.System` as a singleton. It registers one385`IExceptionHandler` with `AddExceptionHandler<WaitlistExceptionHandler>()`,386and calls `UseExceptionHandler()` and `AddProblemDetails()`; the fence387leaves those registrations and the handler out. The handler maps388`WaitlistEntryNotFound` to 404 and `WaitlistEntryAlreadyOffered` to389409, each with problem details, so neither refusal reaches the caller390as a 500 (rule 7). `OfferWaitlistEntry` asks the `TimeProvider` once391and passes that value to `Offer`, so the time comes from a collaborator392passed in rather than from a static call, which keeps393`oo-designing-for-testability` rule 5. It loads the entry, sends394`Offer`, and calls `SaveChangesAsync` once, so the use case is one unit395of work (rule 5).396The endpoint binds the route value and calls the application service;397it neither tests the status nor writes a field. The fence stores the398offered entry under its id in the waitlist table, inside the request's399scope, with the one `SaveChangesAsync` the application service calls.400The state keeps rules 3 and 5: the entity owns the check, and the use401case owns one save.402403## Red flags404405Places to look, not verdicts. A red flag becomes a finding only with406evidence: a measurement, a reproducible bug, or a failing test.407408- A singleton, a hosted service, a middleware constructor or a static409 field that holds a `DbContext` or another scoped service.410- `AddSingleton` or `AddTransient` for a service that holds a411 `DbContext`, or an `AddDbContext` overload that asks for a lifetime412 longer than the request.413- An entity with a public setter, or a public parameterless414 constructor added only for the store.415- An endpoint, a middleware or a controller that reads an entity's416 state, decides, and then sets it.417- An `ExecuteUpdate` or `ExecuteUpdateAsync` that writes a field a rule418 guards, behind the entity's method.419- More than one `SaveChangesAsync` in one use case, or a save in an420 endpoint and another in the service it calls.421- `AsNoTracking` on an entity the use case then changes.422- A value object mapped as an owned entity type, or a value type423 carrying `[ComplexType]`, `[Timestamp]`, `[ConcurrencyCheck]` or424 another EF attribute.425- A rule that two requests can break with no concurrency token and no426 unique index behind it.427- A domain refusal that reaches the caller as a 500 or an HTML error428 page because no `IExceptionHandler` maps it.429- An `IServiceProvider` parameter in a domain class, or a service430 resolved from `HttpContext.RequestServices` where a constructor431 parameter was available.432433## Common mistakes434435- Registering a service that holds a `DbContext` as a singleton because436 its own fields look stateless.437- Injecting a `DbContext` into a hosted service's constructor, then438 reusing that one context for every sweep.439- Adding a private parameterless constructor for EF Core instead of the440 constructor it binds by parameter name.441- Making an entity's setters public "for EF Core" when a private setter442 is mapped and keeps callers out.443- Calling `SaveChangesAsync` after each change in a use case, so a444 failure leaves the first change stored.445- Using `AsNoTracking` and then changing the entity, expecting the next446 save to write it.447- Mapping a value as an owned entity type and accepting its hidden key448 and reference equality.449- Putting a concurrency token in an attribute on the domain type450 rather than in `OnModelCreating`.451- Catching `DbUpdateConcurrencyException` in the endpoint and deciding452 the domain's refusal there.453- Trusting a validation attribute or a request record to hold a rule454 the domain must keep.455456## Related skills457458- `oo-csharp` holds the language rules this skill applies, including459 its rules on records, nullable reference types and async.460- `oo-inverting-dependencies` decides how collaborators reach an object461 and where the composition root sits.462- `oo-taming-persistence` sets the unit of work and keeps a mapping463 decision in the adapter.464- `oo-encapsulating-state-and-behaviour` keeps state behind methods465 named for domain actions.466- `oo-constructing-valid-objects` makes a constructor refuse broken467 input.468- `oo-working-within-a-framework` decides what a framework may shape and469 what stays in the domain.470- `oo-designing-failure-behaviour` names a refusal and translates an471 outside failure where it crosses a boundary.472- `oo-layering-the-system` keeps an endpoint and a store on their own473 sides of the domain.474- `oo-modeling-values-and-entities` decides value or entity and what475 equality reads.476- `oo-placing-domain-logic` keeps an application service to477 coordination.478- `oo-crossing-system-boundaries` gives each contract its own transfer479 types.480- `oo-designing-aggregates` decides what one transaction changes.481- `oo-designing-repositories` declares a read and a repository in the482 domain's words.483- `oo-separating-presentation-from-domain` splits a screen's state from484 the domain.485486## Further reading487488- [Lifetimes and scopes](references/lifetimes-and-scopes.md)