Introduction
In this final lesson, we will review the ASP.NET Core Web API project as a team member preparing it for production, not simply as a developer adding another feature. A working application is not automatically a maintainable application. Responsibilities must remain in the correct layers, dependencies must be controlled, errors must be handled consistently, security risks must be reduced, and the release process must be repeatable.
Refactoring means improving the internal structure of code without intentionally changing its observable behavior. Review is the systematic evaluation of architectural and implementation decisions. Release preparation covers testing, configuration, publishing, observability, and rollback planning before the application is deployed.
For the examples, assume that our solution contains Catalog.Api, Catalog.Application, Catalog.Domain, Catalog.Infrastructure, and separate test projects.
1. Final architecture check: dependency direction
The central Clean Architecture rule is that dependencies point toward the inner layers. The Domain layer should not know about the database, ASP.NET Core, HTTP, or external services. The Application layer contains use cases and contracts, but it should not depend directly on infrastructure details such as EF Core. Infrastructure implements contracts defined by Application. The API layer adapts HTTP requests to application use cases.
| Layer | Expected contents | Should not contain |
|---|---|---|
| Domain | Entities, value objects, business rules, domain exceptions | DbContext, controllers, HTTP, configuration |
| Application | DTOs, commands, queries, validators, interfaces, use cases | SQL, HTTP response construction, EF migrations |
| Infrastructure | DbContext, repositories, external service and authentication implementations | The central business rules |
| Presentation/API | Endpoints, authentication, middleware, HTTP mapping | Direct database queries |
Start by inspecting project references:
dotnet list src/Catalog.Api/Catalog.Api.csproj reference
dotnet list src/Catalog.Application/Catalog.Application.csproj reference
dotnet list src/Catalog.Domain/Catalog.Domain.csproj referenceThe expected direction is API to Application and Infrastructure, Infrastructure to Application and Domain, and Application to Domain. If Domain references Infrastructure or API, the architectural boundary has been broken.
2. Redistributing responsibilities
If a controller performs validation, calls a repository, maps entities, manages transactions, and converts exceptions, it has too many responsibilities. A controller should be a thin adapter between the HTTP world and the application layer.
The following implementation is difficult to maintain:
[HttpPost]
public async Task Create(CreateProductRequest request)
{
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest();
var product = new Product(request.Name, request.Price);
_dbContext.Products.Add(product);
await _dbContext.SaveChangesAsync();
return Ok(product);
}This method combines validation, entity construction, persistence, and response mapping. A more maintainable controller delegates the use case:
[HttpPost]
public async Task Create(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var result = await _sender.Send(
new CreateProductCommand(request.Name, request.Price),
cancellationToken);
return CreatedAtAction(
nameof(GetById),
new { id = result.Id },
result);
} In this design, the request model belongs to the API boundary, the command belongs to Application, entity creation enforces domain rules, and persistence is implemented by Infrastructure.
3. Removing unnecessary code and abstractions
Adding an interface to every class or creating a separate service for every method does not automatically create professional architecture. An abstraction is valuable when it protects a boundary, improves testability, or represents a real variation point. If it only increases the number of folders and files, it may be unnecessary.
- Remove unused interfaces, extension methods, and helper classes.
- Question wrappers that have one implementation and no meaningful boundary.
- Replace repeated mapping code with a clear shared mapping method where appropriate.
- Delete obsolete endpoints, DTOs, configuration keys, and commented-out code.
- Break complex methods into smaller methods with intention-revealing names.
Before deleting anything, verify that it is unused through repository search, compilation, and tests. Keeping code “just in case” gradually creates a repository that is harder to understand and maintain.
4. SOLID and readability review
Use SOLID as a review checklist. For Single Responsibility, ask whether a class has one primary reason to change. For Open/Closed, check whether adding a new behavior always requires modifying a large conditional block. For Liskov Substitution, verify that implementations honor the behavior promised by their interfaces. For Interface Segregation, split large interfaces that force consumers to depend on methods they do not use. For Dependency Inversion, ensure that high-level application code depends on abstractions rather than concrete infrastructure types.
Naming is also part of architecture. Names such as DataService, Helper, and Manager are vague. Prefer names that describe behavior, such as ProductSearchService, OrderNumberGenerator, or PriceCalculator.
5. Code analysis and formatting
The .NET SDK includes analyzers that report code-quality and style issues in addition to compiler errors. Define shared team conventions in an .editorconfig file at the solution root.
dotnet restore
dotnet build --configuration Release
dotnet format ./Catalog.sln --verify-no-changes
dotnet test ./Catalog.sln --configuration Release --no-restoredotnet format can apply formatting and analyzer recommendations. In a CI environment, --verify-no-changes ensures that uncommitted formatting differences do not reach the main branch. Do not suppress warnings automatically. Understand the cause first, and if an exception is justified, use a narrowly scoped suppression with an explanation.
6. Error handling and security review
Endpoints should not return unrelated error formats for similar failures. Validation errors, missing resources, authorization failures, and unexpected exceptions should be converted consistently into Problem Details responses by centralized middleware or an exception handler.
Do not expose exception details to clients in production. Stack traces, connection strings, tokens, and internal type names should never be included in an API response. Detailed diagnostic information belongs in logs, correlated with a request or correlation ID. The client should receive a safe and understandable message.
During the security review, ask the following questions:
- Are protected endpoints guarded by the correct policy or role?
- Can a user access another user’s resource by changing only an identifier?
- Do DTOs expose fields that clients should not see or modify?
- Are secrets or connection strings committed to source control?
- Are HTTPS, security headers, and CORS configured appropriately for production?
- Should Swagger be publicly accessible in production, or should it be protected?
7. Evaluating test coverage through behavior
A high test count is not, by itself, a quality metric. What matters is whether critical business behavior is protected. Domain tests should be fast and isolated. Application tests should verify use-case flows with fake repositories or mocked external dependencies. Integration tests should cover a focused set of scenarios where routing, authentication, serialization, and persistence work together.
A practical minimum release set includes:
- Creating a valid resource and verifying the response status.
- Returning the expected validation response for an invalid request.
- Returning 404 for a missing resource.
- Rejecting unauthenticated and unauthorized requests.
- Testing pagination, filtering, sorting, and boundary values.
- Covering critical workflows that require transactions or concurrency handling.
ASP.NET Core integration tests can configure the application host specifically for testing and use an isolated database or data source. Tests must never connect to the production database.
8. API contracts and backward compatibility
Before release, review endpoint names, HTTP methods, status codes, and request and response DTOs. Removing a response field used by a client can create a breaking change. Adding a field is often safer, but serialization settings and client expectations must still be checked.
Do not return unlimited data from collection endpoints. Apply pagination, filtering, and sorting with reasonable default limits. For update and delete operations, explicitly define idempotency, authorization, and resource ownership rules.
9. Release preparation and publishing
Release preparation is more than copying DLL files to a server. Decide how the application will run, how configuration values will be supplied, how database migrations will be controlled, where logs will be stored, and how to recover if deployment fails.
dotnet publish src/Catalog.Api/Catalog.Api.csproj \
--configuration Release \
--output ./artifacts/publishRun the published output locally and perform a smoke test:
dotnet Catalog.Api.dllNever store production secrets in configuration files committed to source control. Use environment variables, a secret store, or the secure configuration mechanism provided by the hosting platform. Confirm that the selected framework-dependent or self-contained deployment model matches the operating system, installed runtime, and operational requirements.
A practical startup checklist can include:
- Does the Release build succeed?
- Do all automated tests pass?
- Does the health check accurately reflect critical dependencies?
- Are database migrations and seed operations controlled?
- Are log levels appropriate for production?
- Are Swagger, CORS, and exception details configured for production?
- Is a rollback or previous-version recovery plan available?
10. Practice: create a release checklist
Create a RELEASE_CHECKLIST.md file at the solution root and adapt the following items to your project:
- [ ] Project references follow the dependency rule
- [ ] No secrets are committed
- [ ] Release build succeeds
- [ ] Unit and integration tests pass
- [ ] API contract changes are documented
- [ ] Database migration is reviewed
- [ ] Production configuration is supplied securely
- [ ] Health check and logging are verified
- [ ] Rollback plan is availableThe purpose of a checklist is not bureaucracy. It is to create a repeatable release process. Over time, these checks can be automated in a CI/CD pipeline.
Short practice exercise
Select one endpoint in your project and complete the following steps:
- List every operation currently performed by its controller.
- Move non-HTTP logic into the Application or Domain layer.
- Remove unnecessary fields from the response DTO.
- Add tests for success, validation failure, not found, and unauthorized access.
- Run
dotnet build --configuration Release,dotnet format --verify-no-changes, anddotnet test. - Run the published application locally and perform a smoke test.
Conclusion
A professional Clean Architecture project is not successful merely because it has the correct folders. Layer responsibilities must be clear, dependencies must point inward, business rules must remain independent from frameworks, and security and error handling must be consistent. Tests should protect important behavior, API contracts should be managed deliberately, and the release process should be repeatable.
The review and refactoring work in this lesson is intended to make the application sustainable, not simply complete. When a developer can identify which layer should change for a new feature, which tests must be updated, and which contracts must remain stable, the architecture is serving its real purpose. The solution developed throughout this course is therefore more than a working example: it is a professional foundation that can evolve with future requirements.
Sources
- https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10/overview
- https://learn.microsoft.com/en-us/dotnet/core/releases-and-support
- https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-format
- https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/overview
- https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-10.0
- https://learn.microsoft.com/aspnet/core/host-and-deploy/