Introduction
In the previous lesson, we tested the domain model and business rules directly. That approach works very well for classes that contain their behavior internally. In a real application, however, services usually depend on external resources such as a database, clock, file system, HTTP client, or another application service. A service that creates these dependencies internally may work in production, but it becomes difficult, slow, and brittle to unit test.
This lesson focuses on designing production code for testability. We will apply the Explicit Dependencies Principle, interfaces, constructor injection, focused responsibilities, and suitable service lifetimes. We will build a service for a product catalog that calculates the selling price of an in-stock product after applying a discount. Instead of accessing a database directly, the service will receive its dependency from the outside, allowing the test to provide a simple in-memory implementation.
Testability is not a trick performed in the test project. It is a design property that makes production code express its responsibilities and dependencies clearly.
1. The core idea of testable design
A class is easier to test when it receives the resources it needs instead of creating those resources itself. Consider a service that creates a database context directly:
public class ProductService { public async Task<Product?> GetAsync(Guid id) { await using var db = new CatalogDbContext(); return await db.Products.FindAsync(id); } }
This design creates several problems. Every test must prepare a real or special database. Connection settings leak into the test code. When database access fails, it becomes difficult to distinguish service behavior from infrastructure behavior. The class is also tightly coupled to one concrete implementation.
A more testable design defines only what the service needs:
public interface IProductReader { Task<Product?> FindByIdAsync(Guid id, CancellationToken cancellationToken = default); }
Now ProductService knows that it needs a component capable of reading products, but it does not need to know how that component works. The production application can use Entity Framework Core, while a unit test can use a small in-memory implementation or, in a later lesson, a Moq mock.
2. Designing services with focused responsibilities
One of the first signs of testable code is that a class has a clear focus. A product service should not simultaneously read from a database, calculate discounts, send email, and create HTTP responses. Separating these responsibilities allows each behavior to be verified with smaller and clearer tests.
public sealed record Product( Guid Id, string Name, decimal Price, int StockQuantity, bool IsActive);public interface IDiscountPolicy { decimal Apply(Product product); }public sealed class StandardDiscountPolicy : IDiscountPolicy { public decimal Apply(Product product) { if (product.Price <= 100m) { return product.Price; } return decimal.Round(product.Price * 0.90m, 2); } }
The application service can now coordinate the use case: the product must exist, be active, and have stock. It does not contain the details of the pricing policy.
public sealed class ProductService { private readonly IProductReader _productReader; private readonly IDiscountPolicy _discountPolicy; public ProductService( IProductReader productReader, IDiscountPolicy discountPolicy) { _productReader = productReader; _discountPolicy = discountPolicy; } public async Task<ProductPriceResult?> GetSellablePriceAsync( Guid productId, CancellationToken cancellationToken = default) { var product = await _productReader.FindByIdAsync(productId, cancellationToken); if (product is null || !product.IsActive || product.StockQuantity <= 0) { return null; } var finalPrice = _discountPolicy.Apply(product); return new ProductPriceResult(product.Id, product.Name, finalPrice); } } public sealed record ProductPriceResult( Guid ProductId, string ProductName, decimal Price);
Constructor injection makes the class's requirements visible. Anyone reading the test can immediately see which components are required to construct the service. This is safer than creating dependencies inside the service with new.
3. Dependency Injection and constructor injection
ASP.NET Core provides a built-in Dependency Injection container. During application startup, interfaces are mapped to concrete implementations. When a service is created, the container passes those dependencies into the constructor parameters.
var builder = WebApplication.CreateBuilder(args); builder.Services.AddScoped<IProductReader, EfProductReader>(); builder.Services.AddScoped<IDiscountPolicy, StandardDiscountPolicy>(); builder.Services.AddScoped<ProductService>(); var app = builder.Build();
Here, ProductService is registered as a concrete service. When a controller or another service requests it, the container resolves IProductReader and IDiscountPolicy for its constructor.
[ApiController] [Route("api/products")] public sealed class ProductsController : ControllerBase { private readonly ProductService _productService; public ProductsController(ProductService productService) { _productService = productService; } [HttpGet("{id:guid}/price")] public async Task<ActionResult<ProductPriceResult>> GetPrice( Guid id, CancellationToken cancellationToken) { var result = await _productService .GetSellablePriceAsync(id, cancellationToken); return result is null ? NotFound() : Ok(result); } }
With constructor injection, the controller or service does not search for dependencies by calling IServiceProvider inside a method. Dependencies remain explicit, and tests can provide test doubles instead of production implementations.
Service lifetimes
Dependency Injection manages not only object creation but also object lifetime:
| Lifetime | Typical use | Important consideration |
|---|---|---|
| Transient | A new instance for each resolution | Small, stateless services |
| Scoped | One instance per web request | Request-scoped resources such as EF Core DbContext |
| Singleton | One instance for the application lifetime | Shared state and thread safety |
EF Core DbContext is registered as scoped by default. A service that uses it should therefore usually be scoped as well. Injecting a scoped dependency directly into a singleton can create lifetime errors or unintended state sharing.
4. Replacing dependencies in a unit test
Before introducing Moq, we can demonstrate the value of testable design with a small fake implementation:
public sealed class InMemoryProductReader : IProductReader { private readonly IReadOnlyCollection<Product> _products; public InMemoryProductReader(IEnumerable<Product> products) { _products = products.ToArray(); } public Task<Product?> FindByIdAsync( Guid id, CancellationToken cancellationToken = default) { var product = _products.FirstOrDefault(item => item.Id == id); return Task.FromResult(product); } }
There is no need to start the production container in this test. We can construct the system directly and pass its dependencies to the constructor:
public sealed class FixedDiscountPolicy : IDiscountPolicy { public decimal Apply(Product product) => product.Price * 0.90m; }public class ProductServiceTests { [Fact] public async Task GetSellablePriceAsync_ActiveProductInStock_ReturnsDiscountedPrice() { // Arrange var productId = Guid.NewGuid(); var product = new Product( productId, "Mechanical Keyboard", 200m, 5, true); var reader = new InMemoryProductReader(new[] { product }); var policy = new FixedDiscountPolicy(); var service = new ProductService(reader, policy); // Act var result = await service.GetSellablePriceAsync(productId); // Assert result.Should().NotBeNull(); result!.ProductName.Should().Be("Mechanical Keyboard"); result.Price.Should().Be(180m); } [Fact] public async Task GetSellablePriceAsync_OutOfStockProduct_ReturnsNull() { // Arrange var product = new Product( Guid.NewGuid(), "USB Hub", 40m, 0, true); var reader = new InMemoryProductReader(new[] { product }); var service = new ProductService(reader, new FixedDiscountPolicy()); // Act var result = await service.GetSellablePriceAsync(product.Id); // Assert result.Should().BeNull(); } }
These tests do not use a database, file system, or network connection. They are fast, repeatable, and focused on the behavior of ProductService. The Arrange-Act-Assert structure from the previous lesson is used together with explicit dependency construction.
5. Common mistakes
Creating dependencies inside a service
Calls such as new HttpClient(), new DbContext(), or new DateTime() inside a service make behavior difficult to control. Provide the dependency through an interface or a framework abstraction. For time-related logic, an abstraction such as TimeProvider can be used.
Creating an interface for every class
An interface should represent the boundary of a dependency that may be replaced or represented by different behavior in a test. An interface that merely copies every public method of a class does not automatically improve the design.
Too many constructor dependencies
If a service receives eight or ten dependencies, it probably has multiple responsibilities. Consider separating reporting, pricing, notifications, and data access into smaller application services.
Using a service locator
Resolving services inside a method through IServiceProvider hides dependencies. It makes it harder to understand what the test must provide. Prefer constructor injection whenever possible.
Choosing lifetimes randomly
Singleton does not automatically mean faster. Shared state, thread safety, memory usage, and compatibility with scoped dependencies must all be considered.
6. Short practice exercise
- Define an IClock interface with a DateTimeOffset UtcNow { get; } property.
- Write an OrderExpirationService that receives IClock through its constructor.
- The service should return true when an order's expiration time has passed and false otherwise.
- Create a FixedClock fake that does not use the real system time.
- Write at least three tests for past, future, and exact-boundary timestamps.
Also register the service in the ASP.NET Core container. Remember that the unit test does not have to use the container, but the application must have a correct registration when it runs.
Conclusion
In this lesson, we applied the design decisions that form the foundation of testable code. Services become easier to unit test when they do not create concrete infrastructure dependencies, describe their needs through interfaces, and receive those dependencies through constructor injection. Focused responsibilities also make services more readable and less brittle.
In the next stage, we will represent these explicit dependencies more flexibly with Moq. We will define what a dependency should return for specific inputs, verify that calls were made correctly, and test error scenarios without requiring a database.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/service-lifetimes
- https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/service-registration
- https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices