Volume 2 · Chapter 10 — ASP.NET Core Enterprise Development
Enterprise ASP.NET Core Architecture
10.1 Introduction
Enterprise ASP.NET Core applications need an architecture that supports business growth, team scale, maintainability, security, and operational reliability - one that separates business rules from technical details so the system can evolve without large rewrites. This chapter ties the volume’s building blocks into architectural patterns (layering, Clean Architecture, CQRS, mediator, repository, microservices), all of which Volume 6 and Volume 9 develop in depth; here they are framed in the ASP.NET Core context.
10.2 Layering and Clean Architecture
The standard structure separates presentation (HTTP concerns), application (use cases, workflows), domain (business rules, entities), and infrastructure (databases, messaging, integrations). Clean Architecture enforces the Dependency Rule: dependencies point inward toward the domain, so business logic is independent of frameworks and infrastructure and stays testable and replaceable.
flowchart TB Pres["Presentation (API/controllers)"] --> App["Application (use cases)"] App --> Dom["Domain (entities, rules)"] App --> Infra["Infrastructure (DB, messaging)"] Infra -.-> Dom Dom -. "defines interfaces (ports)" .- Infra
10.3 CQRS and the Mediator Pattern
CQRS separates commands (change state) from queries (read data), letting each be modeled and scaled independently. A mediator (MediatR or a hand-rolled dispatcher) decouples controllers from handlers: a controller sends a command/query object and the mediator routes it to the matching handler, with pipeline behaviors adding validation, logging, and transactions in one place. This keeps controllers thin and cross-cutting concerns centralized.
public sealed record ApprovePayment(Guid PaymentId) : IRequest;
public sealed class ApprovePaymentHandler : IRequestHandler<ApprovePayment>
{
public async Task Handle(ApprovePayment cmd, CancellationToken ct) { /* business logic */ }
}
// Thin controller: just dispatch.
[HttpPost("{id}/approve")]
public Task Approve(Guid id, ISender mediator) => mediator.Send(new ApprovePayment(id));
10.4 Repository, Microservices, and Gateways
The Repository and Unit of Work patterns abstract data access and transaction boundaries (though EF Core’sDbSet/DbContextalready provide much of this - add a repository only when it earns its place). At larger scale, capabilities are split into independently deployable microservices with clear boundaries, API contracts, and resilient (often event-driven) communication, fronted by an API gateway that centralizes routing, authentication, and rate limiting - all covered in depth in Volumes 6 and 9.
10.5 Scalability
Enterprise scalability comes from stateless, horizontally-scaled services behind a load balancer, caching, database optimization, asynchronous processing for non-critical work, and strong observability - the same principles developed across Volumes 7, 8, and 9, applied to ASP.NET Core services.
How do you design a scalable, maintainable enterprise ASP.NET Core system?
I start from clear business boundaries and separation of concerns, then layer in the scalability and operational properties, keeping the design proportional to real needs rather than over-engineering. On structure and maintainability: I separate the application into presentation, application, domain, and infrastructure layers following Clean Architecture’s Dependency Rule, so business logic is independent of the web framework and data access and stays testable and evolvable; controllers are thin and delegate to an application layer (often command/query handlers via a mediator, with pipeline behaviors centralizing validation, logging, and transactions); and I draw boundaries by business capability (bounded contexts) so the system’s structure mirrors the domain and teams can own pieces independently. I apply patterns like CQRS and repositories only where they earn their place, keeping simple areas simple. On scalability: I make services stateless so they scale horizontally behind a load balancer, externalize state to Redis, and cache read-heavy data; I optimize data access (efficient queries, indexing, avoiding N+1) since the database is usually the bottleneck, and use read replicas or a CQRS read model when needed; I offload non-critical work (notifications, projections, long-running operations) to asynchronous, event-driven processing so the request path stays fast; and I design for failure with timeouts, retries, and circuit breakers. On whether to distribute: I often start as a well-structured modular monolith with clean internal boundaries and split into microservices only when a concrete pressure (independent scaling or release cadence) justifies the distribution cost - avoiding a premature distributed system. Cross-cutting concerns (auth, logging, error handling) live in middleware/pipeline behaviors, not scattered in business code, and security is built in throughout. And critically, I build strong observability (structured logging, metrics, distributed tracing, health checks) and solid operational practices (IaC, CI/CD, config/secret management) from the start, because a system you can’t observe and deploy reliably won’t stay healthy at scale. The unifying principle is: clear business boundaries and clean separation for maintainability, stateless horizontal scale plus caching and async for scalability, distribution only when justified, cross-cutting concerns centralized, and observability and automation baked in - which produces an ASP.NET Core system that both scales and remains changeable as the business grows, without paying for complexity it doesn’t need.
When would you keep an ASP.NET Core application as a modular monolith rather than splitting into microservices?
I’d keep it a modular monolith - a single deployable with strong internal module boundaries - whenever I don’t have a concrete, demonstrated need for the independence that microservices buy, which is more often than teams assume. Microservices deliver team and scaling independence at the cost of real distributed- systems complexity: network calls, partial failure, eventual consistency, distributed transactions (sagas), and heavy operational tooling (per-service CI/CD, service discovery, tracing, deployment). A modular monolith gives most of the architectural benefits - clear bounded-context boundaries, separation of concerns, independent evolution of modules - while keeping in-process calls (fast, transactionally simple, easy to debug), one deployment, and one datastore to operate, which is dramatically simpler to build and run. So I keep it a modular monolith when the application is small-to-moderate, when one or a few teams own it (no strong need for independent team autonomy), when the domain boundaries are still being discovered (splitting prematurely cements wrong boundaries and creates a painful distributed monolith), when there’s no component with a genuinely different scaling profile that a shared deployment can’t handle, and when the team lacks the operational maturity to run many services well. I design it well internally - modules with their own namespaces, clear public contracts, and ideally separate database schemas, communicating through explicit interfaces and events - so it’s ready to extract services later. Then I extract a microservice only when a concrete pressure appears: a specific module needs to scale independently (a measured bottleneck), a team needs an independent release cadence the monolith is blocking, or a component needs technology/ isolation the monolith can’t provide. This “modular monolith first, extract on evidence” approach avoids paying microservices’ complexity tax prematurely while preserving the option to distribute selectively, which for most enterprise ASP.NET Core applications is the pragmatic, lower-risk path - I distribute because of a demonstrated need, not by default.
10.6 Production Banking Scenario
A banking platform hosts customer management, payments, transactions, and reporting used by many channels. The architecture evolves along bounded contexts with clean layering and thin controllers dispatching to application handlers, DTO-based API contracts, event-driven messaging for cross-context reactions, centralized security and error handling in middleware, and strong observability. It begins as a modular monolith with clear internal boundaries and extracts high-scale modules like payments into their own services only when payday-peak scaling demands it - scaling and evolving without a risky big-bang rewrite.
Volume 2 Summary and Interview Rapid-Fire
- ASP.NET Core hosting, Kestrel, and the request pipeline
- Middleware and cross-cutting concerns
- Dependency injection internals and lifetimes
- Configuration and the Options pattern
- MVC, routing, and thin controllers
- REST API design (DTOs, versioning, idempotency)
- Authentication and authorization
- Security hardening
- Enterprise architecture patterns
What happens when a request hits ASP.NET Core?
Kestrel parses it into an HttpContext, it flows through the middleware pipeline, routing selects an endpoint, the endpoint runs, and the response flows back out through the middleware.
Why is blocking code dangerous here?
It pins thread-pool threads during waits, causing thread-pool starvation - requests queue and throughput collapses while CPU stays low.
Why authentication before authorization?
Authorization needs the identity that authentication establishes (HttpContext.User), so authentication must run first.
Most common DI bug?
The captive dependency - injecting a scoped service into a singleton; fix with IServiceScopeFactory and enable ValidateScopes.
IOptions vs IOptionsSnapshot vs IOptionsMonitor?
IOptions reads once (static); IOptionsSnapshot re-reads per request; IOptionsMonitor gives current value plus change notifications for singletons.
Why expose DTOs, not entities?
Stable contract, no accidental data exposure or over-posting, and the internal model can evolve independently.
Why idempotency keys on payments?
So a retried request (from a timeout or double-click) returns the original result instead of charging twice.
Prevent SQL injection?
Parameterized queries or an ORM - never concatenate user input into SQL.
Role-based vs policy-based authorization?
Role-based checks role membership (coarse); policy-based evaluates claims and custom handlers for nuanced, business-specific rules.
Modular monolith or microservices first?
Start modular monolith with clean boundaries; extract microservices only on evidence of a real scaling or autonomy need.