Enterprise applications aren't just larger demos. They need security, scalability, resilience, observability, and long-term maintainability baked into every layer. ASP.NET Core gives you a great runtime — but real production-readiness comes from combining the right NuGet packages in the right architectural layers. I've worked on enough production codebases to know that the difference between a system that survives three years of feature evolution and one that becomes a rewrite candidate usually comes down to a handful of deliberate package choices. This guide covers the 8 packages that handle 90% of production requirements.

Clean Architecture Layers — Where Each Package Lives

Before reaching for any package, it's worth being deliberate about which layer it belongs to. Each NuGet package should live only in the layer it serves — leaking infrastructure concerns into your domain or application layer is how codebases become fragile. Here's the four-layer map we'll use throughout this guide:

Domain Layer
  • ✓ Business entities
  • ✓ Core business rules
  • ✓ Value objects
  • ✓ No framework deps
Application Layer
  • ✓ Use cases (CQRS)
  • ✓ Commands & Queries
  • ✓ Validation logic
  • ✓ Orchestration
Infrastructure Layer
  • ✓ Database access
  • ✓ External services
  • ✓ Logging sinks
  • ✓ Background jobs
Presentation Layer
  • ✓ API controllers
  • ✓ Authentication
  • ✓ API documentation
  • ✓ Serialization
01
Entity Framework Core Microsoft.EntityFrameworkCore · ORM / Data Access · Infrastructure Layer

EF Core is the dominant ORM in .NET. It maps strongly-typed C# classes to database tables, eliminates boilerplate SQL for standard CRUD operations, and gives you compile-time safety that raw ADO.NET simply can't match. For enterprise teams, the migration system alone is worth the adoption — schema evolution without manual scripts is a significant operational win.

Why enterprises choose EF Core:

  • Compile-time safety through strongly typed models — catch errors before runtime
  • Built-in database migrations for schema evolution without manual scripts
  • Change tracking and optimistic concurrency handling out of the box
  • Excellent support for Domain-Driven Design repository patterns
  • Rich LINQ query composition with deferred execution
💡 Keep DbContext inside Infrastructure only. Expose repositories via interfaces defined in the Application layer. Never let EF Core entities leak into your Presentation layer — use DTOs or response models at the API boundary.

DbContext setup:

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options) { }

    public DbSet<Product> Products => Set<Product>();
}

Repository implementation:

public class ProductRepository : IProductRepository
{
    private readonly AppDbContext _context;

    public ProductRepository(AppDbContext context)
        => _context = context;

    public async Task AddAsync(Product product)
    {
        _context.Products.Add(product);
        await _context.SaveChangesAsync();
    }
}
02
Dapper Dapper · Micro-ORM / Read Performance · Infrastructure Layer

Dapper is a razor-thin wrapper over ADO.NET. It maps SQL results to objects with near-zero overhead and gives you complete SQL control — no query translation surprises, no hidden N+1 problems. It doesn't replace EF Core; it complements it perfectly in a CQRS setup.

💡 The Gold Standard Pattern — CQRS Data Access: Use EF Core for Commands (writes) and Dapper for Queries (reads). This split delivers maintainable write operations with domain integrity, paired with maximum read performance.

Why enterprises add Dapper alongside EF Core:

  • Extremely fast execution — benchmarks consistently show near-raw-ADO.NET speed
  • Zero change tracking overhead for read-only queries
  • Complex reporting queries are often easier and faster to write in SQL directly
  • Gradual migration: introduce Dapper for read models without touching existing write logic

Read repository using Dapper:

public class ProductReadRepository
{
    private readonly IDbConnection _connection;

    public ProductReadRepository(IDbConnection connection)
        => _connection = connection;

    public async Task<IEnumerable<ProductDto>> GetAllAsync()
    {
        const string sql = "SELECT Id, Name, Price FROM Products WHERE IsActive = 1";
        return await _connection.QueryAsync<ProductDto>(sql);
    }
}
03
MediatR MediatR · CQRS Mediator · Application Layer

MediatR implements the Mediator pattern — it routes requests to their handlers without direct coupling between the sender and receiver. It's the backbone of clean CQRS in .NET: thin controllers that dispatch commands and queries, testable handlers that contain all the business logic, and a pipeline that makes cross-cutting concerns trivial to add.

Problems MediatR solves:

  • Fat controllers bloated with service injections and orchestration logic
  • Tight coupling between API layer and business logic — making unit tests painful
  • Cross-cutting concerns (logging, validation, caching) tangled in service methods
  • Notification fan-out to multiple handlers without explicit dependencies

Command definition:

public record CreateProductCommand(string Name, decimal Price)
    : IRequest<Guid>;

Command handler:

public class CreateProductHandler : IRequestHandler<CreateProductCommand, Guid>
{
    private readonly IProductRepository _repository;

    public CreateProductHandler(IProductRepository repository)
        => _repository = repository;

    public async Task<Guid> Handle(
        CreateProductCommand request,
        CancellationToken cancellationToken)
    {
        var product = new Product
        {
            Id    = Guid.NewGuid(),
            Name  = request.Name,
            Price = request.Price
        };

        await _repository.AddAsync(product);
        return product.Id;
    }
}

Thin controller — the entire controller is just a dispatcher:

[ApiController, Route("api/products")]
public class ProductsController : ControllerBase
{
    private readonly IMediator _mediator;

    public ProductsController(IMediator mediator)
        => _mediator = mediator;

    [HttpPost]
    public async Task<IActionResult> Create(CreateProductCommand command)
    {
        var id = await _mediator.Send(command);
        return Ok(id);
    }
}
04
FluentValidation FluentValidation · Input Validation · Application Layer

FluentValidation provides an expressive, readable API for defining validation rules as first-class objects. Instead of scattering [Required] and [MaxLength] attributes across your models, you get dedicated validator classes that are easy to read, easy to test, and easy to extend. It integrates cleanly with MediatR pipeline behaviors for automatic pre-handler validation.

Why FluentValidation outperforms DataAnnotations:

  • Validation logic lives in dedicated classes — not scattered across models as attributes
  • Complex cross-field rules and conditional validation are natural to express
  • Validators are independently unit-testable without spinning up a controller
  • Integrates with MediatR pipeline behaviors for automatic pre-handler validation

Validator for the CreateProductCommand:

public class CreateProductCommandValidator
    : AbstractValidator<CreateProductCommand>
{
    public CreateProductCommandValidator()
    {
        RuleFor(x => x.Name)
            .NotEmpty().WithMessage("Product name is required.")
            .MaximumLength(100).WithMessage("Name cannot exceed 100 characters.");

        RuleFor(x => x.Price)
            .GreaterThan(0).WithMessage("Price must be a positive value.");
    }
}
05
Serilog Serilog · Structured Logging · Infrastructure Layer

Serilog brings structured, machine-readable logging to .NET. Instead of writing plain text strings that you can only grep through, Serilog emits JSON-structured events where each property is a named, queryable field. In production, that difference is enormous — you can filter by ProductId, UserId, or Price directly in Seq, Elasticsearch, Datadog, or Azure Monitor.

Why structured logging matters:

  • JSON-structured events can be queried by field — not just text-searched
  • Correlation IDs propagate automatically across async request chains
  • Multiple sinks (console, file, cloud) configured declaratively
  • Enrichers automatically append environment, machine, and request context

Bootstrap configuration in Program.cs:

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .Enrich.WithMachineName()
    .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message}{NewLine}{Exception}")
    .WriteTo.File("logs/app-.log", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog();

Structured log usage — properties are captured as named fields, not interpolated strings:

// Properties are captured as structured fields, not interpolated into a string
_logger.LogInformation(
    "Product {ProductId} created with price {Price:C} by user {UserId}",
    product.Id, product.Price, currentUser.Id);
06
Polly Polly · Resilience & Transient Fault Handling · Infrastructure Layer

Polly is the .NET resilience library. It gives you retry, circuit-breaker, timeout, and fallback strategies that you compose declaratively and attach to your HTTP clients or service calls. In enterprise systems that integrate with payment gateways, third-party APIs, or microservices, Polly is what stands between a transient network hiccup and a cascading failure.

Failure scenarios Polly handles:

  • Transient HTTP 503 or timeout errors from third-party APIs — retry with exponential backoff
  • Repeated downstream failures — circuit breaker opens to prevent resource exhaustion
  • Slow dependencies — timeout policy cuts long-running requests before threads are blocked
  • Degraded services — fallback returns cached or default data gracefully

Resilience pipeline with retry and circuit breaker:

var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .OrResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
    .WaitAndRetryAsync(
        retryCount: 3,
        sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)),
        onRetry: (outcome, timespan, retry, _) =>
            Log.Warning("Retry {Retry} after {Delay}s: {Reason}",
                retry, timespan.TotalSeconds, outcome.Exception?.Message));

builder.Services
    .AddHttpClient<IExternalService, ExternalService>()
    .AddPolicyHandler(retryPolicy);
07
Swashbuckle / Scalar Swashbuckle.AspNetCore · OpenAPI Documentation · Presentation Layer

Swashbuckle auto-generates OpenAPI 3.0 documentation directly from your controller attributes and XML comments. The result is a living API contract — always in sync with your actual code, never a stale Word document. For enterprise teams with frontend developers, QA engineers, and third-party integrators, this is non-negotiable.

Why enterprises mandate API documentation:

  • Provides a single source of truth for frontend teams and third-party integrators
  • Accelerates developer onboarding — new team members can explore endpoints interactively
  • Enables client SDK generation for TypeScript, Python, and other consumers
  • Swagger UI allows QA and product teams to test endpoints without Postman

Registration in Program.cs:

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title   = "Product API",
        Version = "v1",
        Description = "Enterprise product management API"
    });
    c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "MyApi.xml"));
});

app.UseSwagger();
app.UseSwaggerUI();
08
System.Text.Json System.Text.Json · JSON Serialization · Presentation / Shared

System.Text.Json is the high-performance, built-in JSON serializer that ships with .NET. It allocates significantly less memory than Newtonsoft.Json and is deeply integrated with ASP.NET Core's pipeline. For most enterprise applications on .NET 6+, it's the right default — and with source generators in .NET 7+, you can push it even further with AOT-compatible, allocation-free serialization.

When to use System.Text.Json vs Newtonsoft.Json:

  • Prefer System.Text.Json for all new .NET 6+ projects — it's faster and built-in
  • Newtonsoft.Json remains valid for projects requiring polymorphic deserialization complexity
  • Source generators in .NET 7+ enable AOT-compatible, allocation-free serialization
  • Custom converters handle edge cases (TimeSpan, enums as strings, custom date formats)

Global configuration in Program.cs:

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        var opts = options.JsonSerializerOptions;
        opts.PropertyNamingPolicy  = JsonNamingPolicy.CamelCase;
        opts.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
        opts.WriteIndented          = builder.Environment.IsDevelopment();
        opts.Converters.Add(new JsonStringEnumConverter());
    });

Quick Reference — All 8 Packages at a Glance

# Package Layer Primary Role
01EF CoreInfrastructureWrite operations, domain persistence, migrations
02DapperInfrastructureHigh-performance read queries, reporting, CQRS reads
03MediatRApplicationCQRS mediator, thin controllers, pipeline behaviors
04FluentValidationApplicationCentralized, testable validation rules
05SerilogInfrastructureStructured logging, observability, production diagnostics
06PollyInfrastructureResilience — retry, circuit breaker, timeout, fallback
07SwashbucklePresentationOpenAPI docs, live contract, SDK generation
08System.Text.JsonSharedFast, built-in JSON serialization

Building for the Long Term

These eight packages form a complementary foundation — not a checklist to add blindly. The power comes from how they work together: MediatR routes requests, FluentValidation gates them, EF Core persists the writes, Dapper accelerates the reads, Polly shields external calls, Serilog records everything, Swagger documents it all, and System.Text.Json moves data efficiently across the wire.

Place each package in its correct architectural layer, expose dependencies through interfaces, and you'll have a codebase that is easy to unit test, straightforward to reason about, and built to survive years of feature evolution.

Enterprise readiness isn't about adding every package available — it's about choosing the right ones deliberately, understanding what problem each solves, and applying consistent patterns across your entire application.

Related Articles