Why Should You Use Clean Architecture?

Listen to this Post

Clean Architecture, Hexagonal Architecture, and Onion Architecture share similar principles, focusing on the direction of dependencies toward the center, where the core contains domain entities and business rules. This core remains independent of external concerns, ensuring stability and testability. By decoupling business rules from framework-specific code, these architectures enhance maintainability and scalability.

Key Benefits:

  1. Stability: Business rules remain unaffected by changes in external layers.
  2. Testability: Abstractions allow for easy mocking and testing of business logic.

You Should Know:

Here are some practical commands and code snippets to implement Clean Architecture principles:

  1. Setting Up a Clean Architecture Project in .NET
    dotnet new sln -n CleanArchitecture
    dotnet new classlib -n Core
    dotnet new classlib -n Infrastructure
    dotnet new webapi -n Api
    dotnet sln add Core
    dotnet sln add Infrastructure
    dotnet sln add Api
    

2. Defining Domain Entities

// Core/Entities/Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

3. Creating Abstractions for Repositories

// Core/Interfaces/IRepository.cs
public interface IRepository<T> where T : class
{
Task<T> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(T entity);
}

4. Implementing the Repository in Infrastructure

// Infrastructure/Repositories/ProductRepository.cs
public class ProductRepository : IRepository<Product>
{
private readonly AppDbContext _context;
public ProductRepository(AppDbContext context)
{
_context = context;
}

public async Task<Product> GetByIdAsync(int id)
{
return await _context.Products.FindAsync(id);
}

public async Task<IEnumerable<Product>> GetAllAsync()
{
return await _context.Products.ToListAsync();
}

public async Task AddAsync(Product product)
{
await _context.Products.AddAsync(product);
await _context.SaveChangesAsync();
}

public async Task UpdateAsync(Product product)
{
_context.Products.Update(product);
await _context.SaveChangesAsync();
}

public async Task DeleteAsync(Product product)
{
_context.Products.Remove(product);
await _context.SaveChangesAsync();
}
}

5. Dependency Injection in Startup

// Api/Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddScoped<IRepository<Product>, ProductRepository>();
services.AddControllers();
}

6. Testing with Mocking

// Unit Tests
public class ProductServiceTests
{
private readonly Mock<IRepository<Product>> _mockRepo;
private readonly ProductService _productService;

public ProductServiceTests()
{
_mockRepo = new Mock<IRepository<Product>>();
_productService = new ProductService(_mockRepo.Object);
}

[Fact]
public async Task GetProductById_ReturnsProduct()
{
var product = new Product { Id = 1, Name = "Test Product", Price = 100 };
_mockRepo.Setup(repo => repo.GetByIdAsync(1)).ReturnsAsync(product);

var result = await _productService.GetProductById(1);

Assert.Equal(product, result);
}
}

What Undercode Say:

Clean Architecture is a powerful approach to building scalable and maintainable applications. By focusing on decoupling business logic from external dependencies, it ensures long-term stability and ease of testing. Whether you’re working on a small project or a large enterprise application, adopting Clean Architecture principles can significantly improve your development workflow. For further reading, check out the Clean Architecture Template provided by Milan Jovanović.

Related Commands:

  • dotnet new: Create new .NET projects.
  • dotnet add reference: Add project references.
  • dotnet test: Run unit tests.
  • dotnet ef migrations add: Add database migrations.
  • dotnet ef database update: Update the database schema.

By following these practices, you can build robust, testable, and maintainable applications that stand the test of time.

References:

Reported By: Milan Jovanovic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

Whatsapp
TelegramFeatured Image