Specification
Reusable, testable query logic for your data access
Overview
As applications grow, the same queries get rewritten in controllers, services, and repositories. Small differences creep in, such as a missing filter here or a forgotten include there, and repositories swell with one-off methods that are hard to test.
Ardalis.Specification gives each query a name and a home:
public sealed class ActiveCustomersByRegionSpec : Specification<Customer>
{
public ActiveCustomersByRegionSpec(string region) =>
Query.Where(c => c.IsActive && c.Region == region)
.OrderBy(c => c.Name);
}
var customers = await repository.ListAsync(new ActiveCustomersByRegionSpec("West"));
What your organization gains
- Consistent business rules. A query is defined once and reused everywhere, so every screen and report agrees.
- Leaner repositories. A small, generic repository replaces dozens of special-purpose query methods.
- Better test coverage. Query logic can be unit tested in isolation, without a database.
- Less code to own. Query evaluation and ORM integration are already built and tested.
How It Compares
| Feature | No Pattern | Custom Implementation | Specification |
|---|---|---|---|
| Benefits of the Specification pattern | |||
| Query logic defined once and reused everywhere | No | Yes | Yes |
| Queries have intention-revealing names | No | Yes | Yes |
| Repositories stay small and generic | No | Yes | Yes |
| Query logic unit testable without a database | No | Yes | Yes |
| Consistent filtering, ordering, paging, and includes | No | Yes | Yes |
| Benefits of a maintained package used by tens of thousands of developers | |||
| Battle-tested in production by tens of thousands of developers | No | No | Yes |
| Bugs found and fixed by a large user community | No | No | Yes |
| Pattern code your team doesn’t have to write, test, or maintain | No | No | Yes |
| Kept current with new .NET releases | No | No | Yes |
| Ready-made Entity Framework Core and EF6 integration | No | No | Yes |
| Documentation and samples that speed up onboarding | No | No | Yes |
| Already familiar to many developers before they join your team | No | No | Yes |
| Professionally maintained and supported by NimbleTools | No | No | Yes |
Get the package on NuGet with dotnet add package Ardalis.Specification.
Key Features
- Fluent builder for filtering, ordering, paging, and includes
- Entity Framework Core and Entity Framework 6 integration
- Generic repository base classes built on specifications
- In-memory evaluation for fast unit tests