Query logic has a habit of spreading. The same Where and Include calls get copied into every handler that loads an order, and sooner or later one copy drifts from the rest. The Specification pattern gives each of those queries a name and a single home, so every caller loads the data the same way.
Let's take the example below of adding items to, or removing items from, an order. When looking up the order we need to include the current OrderItems and ensure the order is not complete. This logic is duplicated in both the AddItem and RemoveItem methods, which violates the DRY principle.
Even worse, if the logic changes, we need to update it in multiple places, increasing the risk of bugs and inconsistencies. Below we correctly check the order's status when adding items, but not when removing them, which is a bug.
public class OrderService(ApplicationDbContext dbContext){public async Task AddItem(Guid orderId, OrderItem item, CancellationToken ct){var order = await dbContext.Orders.Include(o => o.OrderItems).FirstOrDefaultAsync(o => o.Id == orderId && o.Status != OrderStatus.Complete, ct)?? throw new KeyNotFoundException($"Incomplete order {orderId} not found");order.AddItem(item);await dbContext.SaveChangesAsync(ct);}public async Task RemoveItem(Guid orderId, OrderItem item, CancellationToken ct){// Duplicated logic and bug introduced by not checking OrderStatusvar order = await dbContext.Orders.Include(o => o.OrderItems).FirstOrDefaultAsync(o => o.Id == orderId, ct)?? throw new KeyNotFoundException($"Order {orderId} not found");order.RemoveItem(item);await dbContext.SaveChangesAsync(ct);}}
❌ Figure: Bad example - Duplicated query logic to fetch the order
The Specification pattern is a design pattern used to define business rules in a reusable and composable way. It encapsulates the logic of a business rule into a single unit, making it easy to test, reuse, and combine with other specifications.
Include an aggregate needs, so every caller loads it fully and its invariants can be enforcedSpecifications are not the only way to remove duplicated query logic. Here is how they compare with the two most common alternatives.
Put each query behind a method on a repository built for one aggregate (e.g. IOrderRepository, not a generic IRepository<T>).
public class OrderRepository(ApplicationDbContext dbContext) : IOrderRepository{public Task<Order?> GetIncompleteOrderById(Guid orderId, CancellationToken ct) =>dbContext.Orders.Include(o => o.OrderItems).FirstOrDefaultAsync(o => o.Id == orderId && o.Status != OrderStatus.Complete, ct);}
Figure: A specific repository method encapsulating the order query
GetById, GetByIdWithItems, GetIncompleteById...) changes the interface, its implementation and every mock of itPut the query in an extension method on IQueryable<T>.
public static class OrderQueryExtensions{public static IQueryable<Order> IncompleteOrderById(this IQueryable<Order> query, Guid orderId) =>query.Include(o => o.OrderItems).Where(o => o.Id == orderId && o.Status != OrderStatus.Complete);}
Figure: An extension method encapsulating the order query
Include comes from EF Core, so the code that defines the query must reference EF Core. That usually means it can't live in the Domain layerPut the query in a static factory method on a specification class for the aggregate (e.g. OrderSpec.IncompleteById(orderId)), as shown in Using the Specification Pattern below.
Include, split queries, AsNoTracking, ordering and paging| Specific repositories | Extension methods | Specifications | |
|---|---|---|---|
| Removes duplicated queries | ✅ | ✅ | ✅ |
| Query logic lives in the Domain layer | ❌ (only the interface) | ❌ | ✅ |
| A new query is one change in one place | ❌ | ✅ | ✅ |
| Standard, consistent shape | ✅ | ❌ | ✅ |
| No third-party dependency | ✅ | ✅ | ❌ |
Figure: Comparison of approaches to encapsulating data access
Specifications earn their place when a query is reused or loads an aggregate. Don't create one for every query.
Use a specification when either is true:
Include it needs must be thereQuery inline when both are true:
Steve Smith (aka "Ardalis") has created an excellent library called Ardalis.Specification that integrates well with EF Core.
Create one specification class per aggregate, and add a static factory method for each query. Every query for an aggregate then lives in one file, and each call site says exactly what it loads: TeamSpec.ById(teamId). With a class per query (TeamByIdSpec, TeamByNameSpec...), the queries end up scattered across many small files.
public sealed class TeamSpec : Specification<Team>{public static TeamSpec ById(TeamId teamId){var spec = new TeamSpec();spec.Query.Where(t => t.Id == teamId).Include(t => t.Missions).Include(t => t.Heroes);return spec;}}
The base class is Specification<T>, not SingleResultSpecification<T>, because one class holds both single-result and list queries, and a list query needs ordering and paging on a type that doesn't claim to return one row. The single-result marker only matters to the Ardalis repository's SingleOrDefaultAsync, so SingleOrDefaultAsync(TeamSpec.ById(teamId)) won't compile. Apply the spec with WithSpecification(...) and end the query yourself, e.g. with FirstOrDefaultAsync.
var teamId = TeamId.From(request.TeamId);var team = await dbContext.Teams.WithSpecification(TeamSpec.ById(teamId)).FirstOrDefaultAsync(ct);
For end-to-end examples of the specification pattern see the SSW.VerticalSliceArchitecture Template and the SSW.CleanArchitecture Template.
Re-visiting the example above, we can apply the Specification pattern as follows:
public sealed class OrderSpec : Specification<Order>{public static OrderSpec IncompleteById(Guid orderId){var spec = new OrderSpec();spec.Query.Where(o => o.Id == orderId && o.Status != OrderStatus.Complete).Include(o => o.OrderItems);return spec;}}public class OrderService(ApplicationDbContext dbContext){public async Task AddItem(Guid orderId, OrderItem item, CancellationToken ct){var order = await dbContext.Orders.WithSpecification(OrderSpec.IncompleteById(orderId)).FirstOrDefaultAsync(ct)?? throw new KeyNotFoundException($"Incomplete order {orderId} not found");order.AddItem(item);await dbContext.SaveChangesAsync(ct);}public async Task RemoveItem(Guid orderId, OrderItem item, CancellationToken ct){var order = await dbContext.Orders.WithSpecification(OrderSpec.IncompleteById(orderId)).FirstOrDefaultAsync(ct)?? throw new KeyNotFoundException($"Incomplete order {orderId} not found");order.RemoveItem(item);await dbContext.SaveChangesAsync(ct);}}
✅ Figure: Good example - Specification used to keep Order query logic DRY