Convert Figma logo to code with AI

ardalis logoCleanArchitecture

Clean Architecture Solution Template: A proven Clean Architecture Template for ASP.NET Core 10

18,332
3,068
18,332
40

Top Related Projects

Clean Architecture Solution Template for ASP.NET Core

Sample ASP.NET Core 8.0 reference application, now community supported: https://github.com/NimblePros/eShopOnWeb

:cyclone: Clean Architecture with .NET6, C#10 and React+Redux. Use cases as central organizing structure, completely testable, decoupled from frameworks

Web Application ASP.NET 9 using Clean Architecture, DDD, CQRS, Event Sourcing and a lot of good practices

Full Modular Monolith application with Domain-Driven Design approach.

Northwind Traders is a sample application built using ASP.NET Core and Entity Framework Core.

Quick Overview

CleanArchitecture is a sample application built with ASP.NET Core following the principles of Clean Architecture. It demonstrates how to structure a .NET application with a clear separation of concerns, making it easier to maintain, test, and evolve over time.

Pros

  • Provides a clear and organized project structure
  • Demonstrates SOLID principles and dependency inversion
  • Includes examples of domain-driven design concepts
  • Offers a good starting point for building scalable applications

Cons

  • May be overly complex for small projects
  • Requires a learning curve for developers unfamiliar with Clean Architecture
  • Some might find the number of projects/layers excessive
  • Could lead to over-engineering if not applied judiciously

Code Examples

  1. Domain Entity:
public class ToDoItem : BaseEntity
{
    public string Title { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public bool IsDone { get; private set; }

    public void MarkComplete()
    {
        IsDone = true;
    }
}

This code defines a ToDoItem entity with properties and a method to mark it as complete.

  1. Application Service:
public class CreateToDoItemCommand : IRequest<int>
{
    public string Title { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
}

public class CreateToDoItemCommandHandler : IRequestHandler<CreateToDoItemCommand, int>
{
    private readonly IRepository<ToDoItem> _repository;

    public CreateToDoItemCommandHandler(IRepository<ToDoItem> repository)
    {
        _repository = repository;
    }

    public async Task<int> Handle(CreateToDoItemCommand request, CancellationToken cancellationToken)
    {
        var item = new ToDoItem
        {
            Title = request.Title,
            Description = request.Description
        };

        await _repository.AddAsync(item);

        return item.Id;
    }
}

This example shows a command and its handler for creating a new ToDoItem.

  1. API Controller:
[ApiController]
[Route("api/[controller]")]
public class ToDoItemsController : ControllerBase
{
    private readonly IMediator _mediator;

    public ToDoItemsController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public async Task<ActionResult<int>> Create(CreateToDoItemCommand command)
    {
        return await _mediator.Send(command);
    }
}

This controller demonstrates how to use MediatR to handle the creation of a ToDoItem.

Getting Started

  1. Clone the repository:

    git clone https://github.com/ardalis/CleanArchitecture.git
    
  2. Open the solution in Visual Studio or your preferred IDE.

  3. Set the Web project as the startup project.

  4. Run the application using IIS Express or by executing:

    dotnet run --project src/CleanArchitecture.Web
    
  5. Navigate to https://localhost:5001 in your browser to see the application running.

Competitor Comparisons

Clean Architecture Solution Template for ASP.NET Core

Pros of CleanArchitecture (Jason Taylor)

  • More comprehensive, including features like authentication, authorization, and API versioning
  • Utilizes modern .NET features and patterns, such as Minimal APIs and Vertical Slice Architecture
  • Includes a robust testing suite with examples of unit, integration, and functional tests

Cons of CleanArchitecture (Jason Taylor)

  • May be overwhelming for beginners due to its complexity and extensive feature set
  • Opinionated approach might not fit all project requirements or team preferences
  • Steeper learning curve compared to simpler implementations

Code Comparison

CleanArchitecture (Jason Taylor):

public sealed class CreateTodoItemCommandHandler : IRequestHandler<CreateTodoItemCommand, int>
{
    private readonly IApplicationDbContext _context;

    public CreateTodoItemCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

CleanArchitecture (Ardalis):

public class CreateProjectCommandHandler : IRequestHandler<CreateProjectCommand, int>
{
  private readonly IRepository<Project> _repository;

  public CreateProjectCommandHandler(IRepository<Project> repository)
  {
    _repository = repository;
  }

Both examples showcase similar command handler structures, but Jason Taylor's implementation uses a custom database context interface, while Ardalis' version utilizes a generic repository pattern.

Sample ASP.NET Core 8.0 reference application, now community supported: https://github.com/NimblePros/eShopOnWeb

Pros of eShopOnWeb

  • More comprehensive e-commerce example with real-world scenarios
  • Includes additional features like basket management and ordering
  • Better documentation and explanations of architectural decisions

Cons of eShopOnWeb

  • More complex and potentially overwhelming for beginners
  • Less focused on clean architecture principles
  • Harder to extract and apply to non-e-commerce projects

Code Comparison

CleanArchitecture:

public class DeleteProjectCommand : IRequest
{
    public int Id { get; set; }
}

public class DeleteProjectCommandHandler : IRequestHandler<DeleteProjectCommand>
{
    private readonly IRepository<Project> _repository;

    public DeleteProjectCommandHandler(IRepository<Project> repository)
    {
        _repository = repository;
    }

eShopOnWeb:

public class CreateOrderCommand : IRequest<int>
{
    public string BuyerId { get; set; }
    public Address ShippingAddress { get; set; }
    public Address BillingAddress { get; set; }
    public List<OrderItemDTO> Items { get; set; }
}

public class CreateOrderCommandHandler : IRequestHandler<CreateOrderCommand, int>
{
    private readonly IOrderRepository _orderRepository;

Both repositories demonstrate CQRS pattern usage, but eShopOnWeb's example is more complex, reflecting real-world e-commerce scenarios. CleanArchitecture focuses on simpler, more generic implementations that are easier to adapt to various project types.

:cyclone: Clean Architecture with .NET6, C#10 and React+Redux. Use cases as central organizing structure, completely testable, decoupled from frameworks

Pros of clean-architecture-manga

  • More comprehensive implementation of Clean Architecture principles
  • Includes additional features like CQRS and Event Sourcing
  • Provides a more detailed domain model and use cases

Cons of clean-architecture-manga

  • Higher complexity, which may be overwhelming for beginners
  • Steeper learning curve due to advanced concepts and patterns
  • Less focus on simplicity and ease of understanding

Code Comparison

CleanArchitecture:

public class DeleteProjectHandler : ICommandHandler<DeleteProjectCommand, ProjectDto>
{
    private readonly IRepository<Project> _repository;
    public DeleteProjectHandler(IRepository<Project> repository) => _repository = repository;
    public async Task<ProjectDto> Handle(DeleteProjectCommand request, CancellationToken cancellationToken)
    {
        var projectToDelete = await _repository.GetByIdAsync(request.ProjectId);
        await _repository.DeleteAsync(projectToDelete);
        return new ProjectDto(projectToDelete.Id, projectToDelete.Name);
    }
}

clean-architecture-manga:

public sealed class CloseAccountUseCase : ICloseAccountUseCase
{
    private readonly IAccountRepository _accountRepository;
    private readonly IUnitOfWork _unitOfWork;
    public CloseAccountUseCase(IAccountRepository accountRepository, IUnitOfWork unitOfWork)
    {
        _accountRepository = accountRepository;
        _unitOfWork = unitOfWork;
    }
    public async Task<CloseAccountOutput> Execute(CloseAccountInput input)
    {
        var account = await _accountRepository.Get(input.AccountId);
        if (account == null) throw new AccountNotFoundException($"The account {input.AccountId} does not exist or is already closed.");
        account.Close();
        await _accountRepository.Update(account);
        await _unitOfWork.Save();
        return new CloseAccountOutput(account);
    }
}

Web Application ASP.NET 9 using Clean Architecture, DDD, CQRS, Event Sourcing and a lot of good practices

Pros of EquinoxProject

  • Implements Event Sourcing and CQRS patterns, providing a more comprehensive approach to domain-driven design
  • Includes integration with Swagger for API documentation
  • Offers a more extensive set of features, including identity management and JWT authentication

Cons of EquinoxProject

  • More complex architecture, which may be overkill for smaller projects
  • Steeper learning curve due to the additional patterns and technologies used
  • Less frequently updated compared to CleanArchitecture

Code Comparison

CleanArchitecture:

public class DeleteToDoItemCommand : IRequest
{
    public int Id { get; set; }
}

EquinoxProject:

public class RegisterNewCustomerCommand : Command
{
    public Guid Id { get; private set; }
    public string Name { get; private set; }
    public string Email { get; private set; }
    public DateTime BirthDate { get; private set; }
}

The EquinoxProject example shows a more detailed command structure with additional properties, reflecting its focus on CQRS and event sourcing. CleanArchitecture's example is simpler, aligning with its more straightforward approach to clean architecture.

Full Modular Monolith application with Domain-Driven Design approach.

Pros of modular-monolith-with-ddd

  • Implements a more comprehensive Domain-Driven Design (DDD) approach
  • Provides a detailed example of modular monolith architecture
  • Includes more advanced patterns like CQRS and Event Sourcing

Cons of modular-monolith-with-ddd

  • More complex structure, potentially steeper learning curve
  • Less focus on Clean Architecture principles
  • May be overkill for smaller projects or teams new to DDD

Code Comparison

CleanArchitecture:

public class DeleteTodoItemCommand : IRequest
{
    public int Id { get; set; }
}

modular-monolith-with-ddd:

public class CreateMeetingGroupCommand : CommandBase<MeetingGroupId>
{
    public string Name { get; }
    public string Description { get; }
    public MeetingGroupLocation Location { get; }
}

The modular-monolith-with-ddd example shows a more detailed command structure with domain-specific types, while CleanArchitecture uses a simpler approach with primitive types.

Both repositories offer valuable insights into structuring .NET applications, but they cater to different levels of complexity and architectural focus. CleanArchitecture provides a cleaner, more straightforward implementation of Clean Architecture principles, while modular-monolith-with-ddd offers a more comprehensive example of DDD and modular monolith patterns.

Northwind Traders is a sample application built using ASP.NET Core and Entity Framework Core.

Pros of NorthwindTraders

  • Implements a more comprehensive set of Clean Architecture principles
  • Includes a broader range of features and technologies (e.g., CQRS, MediatR)
  • Provides a more realistic and complex example of a business application

Cons of NorthwindTraders

  • May be overwhelming for beginners due to its complexity
  • Requires more setup and configuration to get started
  • Has a steeper learning curve compared to CleanArchitecture

Code Comparison

NorthwindTraders:

public class CreateCustomerCommand : IRequest<int>
{
    public string Id { get; set; }
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
}

CleanArchitecture:

public class CreateToDoItemCommand : IRequest<ToDoItemRecord>
{
    public string Title { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
}

Both repositories demonstrate the use of CQRS patterns, but NorthwindTraders shows a more complex command structure with additional properties, reflecting its more comprehensive approach to Clean Architecture principles.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.NET Core publish Ardalis.CleanArchitecture Template to nuget Ardalis.CleanArchitecture.Template on NuGet

Follow @ardalis   Follow @nimblepros

Alt

Clean Architecture

A starting point for Clean Architecture with ASP.NET Core. Clean Architecture is just the latest in a series of names for the same loosely-coupled, dependency-inverted architecture. You will also find it named hexagonal, ports-and-adapters, or onion architecture.

Learn more about Clean Architecture and this template in NimblePros' Introducing Clean Architecture course. Use code ARDALIS to save 20%.

This architecture is used in the DDD Fundamentals course by Steve Smith and Julie Lerman.

:school: Contact Steve's company, NimblePros, for Clean Architecture or DDD training and/or implementation assistance for your team.

Take the Course!

Learn about how to implement Clean Architecture from NimblePros trainers Sarah "sadukie" Dutkiewicz and Steve "ardalis" Smith.

Table Of Contents

Give a Star! :star:

If you like or are using this project to learn or start your solution, please give it a star. Thanks!

Or if you're feeling really generous, we now support GitHub sponsorships - see the button above.

Sponsors

I'm please to announce that Amazon AWS's FOSS fund has chosen to award a 12-month sponsorship to this project. Thank you, and thanks to all of my other past and current sponsors!

Troubleshooting Chrome Errors

By default the site uses HTTPS and expects you to have a self-signed developer certificate for localhost use. If you get an error with Chrome see this answer for mitigation instructions.

Versions

The main branch is now using .NET 9. This corresponds with NuGet package version 10.x. Previous versions are available - see our Releases.

Learn More

Documentation

The official documentation for this template, including Getting Started steps, Migration Guides, and Architectural Decisions, can be found at Ardalis Clean Architecture Docs.

If you are upgrading from an older version, please be sure to review our Migration Guides on the new documentation site!