LESSON 22 OF 22

22. Project Refactoring, Review, and Release Preparation

Review the completed Clean Architecture project, improve its maintainability, verify quality and security, and prepare a repeatable production release process.

75 dk 84

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.

LayerExpected contentsShould not contain
DomainEntities, value objects, business rules, domain exceptionsDbContext, controllers, HTTP, configuration
ApplicationDTOs, commands, queries, validators, interfaces, use casesSQL, HTTP response construction, EF migrations
InfrastructureDbContext, repositories, external service and authentication implementationsThe central business rules
Presentation/APIEndpoints, authentication, middleware, HTTP mappingDirect 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 reference

The 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-restore

dotnet 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/publish

Run the published output locally and perform a smoke test:

dotnet Catalog.Api.dll

Never 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:

  1. Does the Release build succeed?
  2. Do all automated tests pass?
  3. Does the health check accurately reflect critical dependencies?
  4. Are database migrations and seed operations controlled?
  5. Are log levels appropriate for production?
  6. Are Swagger, CORS, and exception details configured for production?
  7. 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 available

The 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:

  1. List every operation currently performed by its controller.
  2. Move non-HTTP logic into the Application or Domain layer.
  3. Remove unnecessary fields from the response DTO.
  4. Add tests for success, validation failure, not found, and unauthorized access.
  5. Run dotnet build --configuration Release, dotnet format --verify-no-changes, and dotnet test.
  6. 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