What Is Onion Architecture?

Learn What Is Onion Architecture? with practical examples, explanations, best practices, and real-world coding techniques.

Onion Architecture is a software architecture style that organizes an application into concentric layers with the most important business logic placed at the center. The main goal is to keep the core of the application independent from external concerns such as databases, web frameworks, UI technologies, and third-party services.

The defining idea of Onion Architecture is that dependencies should point inward toward the core of the system. The business rules should not depend directly on infrastructure or framework details. Instead, outer layers depend on inner layers, while interfaces defined by the inner layers can be implemented by the outer layers.

This approach is commonly used when maintainability, testability, and separation between business rules and technical infrastructure are important architectural goals.

Why Is It Called Onion Architecture?

Onion Architecture is represented as a set of layers wrapped around a central core, similar to the layers of an onion. The center contains the business domain, while outer layers contain application services, infrastructure, and delivery mechanisms.

+--------------------------------------------------+
|                Infrastructure                    |
|                                                  |
|   +------------------------------------------+   |
|   |        Application Services             |   |
|   |                                          |   |
|   |   +----------------------------------+   |   |
|   |   |          Domain Layer            |   |   |
|   |   |                                  |   |   |
|   |   |   Entities / Business Rules      |   |   |
|   |   |                                  |   |   |
|   |   +----------------------------------+   |   |
|   |                                          |   |
|   +------------------------------------------+   |
|                                                  |
+--------------------------------------------------+

Dependencies move toward the center.

The exact number of layers can vary between implementations. What matters most is the dependency direction and the protection of the domain from external technical concerns.

The Core Principle of Onion Architecture

The central rule is simple: inner layers should not depend on outer layers.

For example, the domain should not need to know whether data is stored in PostgreSQL, SQL Server, MongoDB, or another database. It should also not depend on ASP.NET Core, Angular, Entity Framework, or another specific framework.

Infrastructure
      |
      v
Application
      |
      v
Domain

Allowed dependency direction:
Outer  --->  Inner

Not:
Inner  --->  Outer

This dependency direction allows technical implementation details to be replaced without forcing changes to the central business rules.

Layers of Onion Architecture

There is no single mandatory layer naming convention, but Onion Architecture commonly separates the system into domain, application, infrastructure, and presentation or delivery concerns.

Domain Layer

The domain layer is the center of the architecture. It contains the most important business concepts and rules of the system.

  • Entities
  • Value objects
  • Domain rules
  • Domain services where appropriate
  • Business-related interfaces

Application Layer

The application layer coordinates use cases. It determines how the application's business capabilities are executed without owning infrastructure-specific details.

  • Use cases
  • Application services
  • Commands and queries
  • DTOs where appropriate
  • Interfaces required by application operations

Infrastructure Layer

The infrastructure layer contains technical implementations required by the application.

  • Database implementations
  • Repository implementations
  • External API integrations
  • Messaging systems
  • Email providers
  • File storage
  • Caching

Presentation or Delivery Layer

The outer delivery layer handles communication with users or external clients. In a web application this could include controllers, API endpoints, or other delivery mechanisms.

Dependency Inversion in Onion Architecture

Dependency inversion is an important idea behind Onion Architecture. Instead of allowing the application or domain logic to directly depend on a concrete infrastructure implementation, the inner layer can define an abstraction and the outer layer provides the implementation.

For example, the application can define an interface for loading orders:

public interface IOrderRepository
{
    Task<Order?> GetByIdAsync(Guid id);
    Task AddAsync(Order order);
}

The infrastructure layer can then implement that interface:

public class OrderRepository : IOrderRepository
{
    private readonly AppDbContext _db;

    public OrderRepository(AppDbContext db)
    {
        _db = db;
    }

    public async Task<Order?> GetByIdAsync(Guid id)
    {
        return await _db.Orders.FindAsync(id);
    }

    public async Task AddAsync(Order order)
    {
        _db.Orders.Add(order);
        await _db.SaveChangesAsync();
    }
}

The important part is that the business-facing abstraction belongs to an inner layer while the database-specific implementation remains outside the core.

Onion Architecture Example

Consider an order management application. Creating an order may involve validating business rules, saving the order, and publishing an event. These responsibilities can be separated across the architectural layers.

POST /orders
     |
     v
OrdersController
     |
     v
CreateOrderService
     |
     v
Order Domain
     |
     +---- IOrderRepository
     |
     +---- IOrderEventPublisher
                  |
                  v
          Infrastructure
             |
       +-----+------+------+
       |            |      |
    Database      Queue   Other Services

The controller does not need to know how the database works, and the domain does not need to know which message broker is used. These technical decisions remain outside the core business logic.

Benefits of Onion Architecture

Business Logic Independence

Core business rules can remain independent of databases, frameworks, and external services.

Better Testability

Domain and application logic can often be tested without requiring a real database, HTTP server, or external service.

Replaceable Infrastructure

Infrastructure implementations can be replaced while keeping the core business rules stable.

Clear Dependencies

Dependency direction becomes explicit, making architectural relationships easier to understand.

Limitations of Onion Architecture

Onion Architecture introduces structure and abstraction, but those abstractions also add concepts that developers need to understand. It may be unnecessary for very small applications with straightforward requirements.

Challenge Explanation
More abstractions Interfaces and dependency boundaries introduce additional types and concepts.
More project structure A small application may not benefit from several separate layers and projects.
Learning curve Developers need to understand dependency inversion and the purpose of each architectural boundary.
Overengineering risk Adding abstractions without a real architectural need can make a simple system harder to understand.

Onion Architecture vs Layered Architecture

Both architectures use layers, but they place different emphasis on dependency direction and the protection of business logic.

Aspect Layered Architecture Onion Architecture
Main focus Separation of technical responsibilities Dependency direction and domain independence
Core business logic May depend on lower technical layers depending on the design Protected from infrastructure dependencies
Infrastructure Usually a lower-level layer Positioned outside the core
Dependency inversion Not necessarily central to the pattern Central architectural principle

In practice, layered and Onion Architecture can overlap. A system can still use familiar presentation, application, domain, and infrastructure responsibilities while applying inward dependency rules.

Onion Architecture in ASP.NET Core

A common ASP.NET Core implementation separates projects according to responsibilities and keeps infrastructure-specific dependencies outside the domain.

MyApplication.Domain/
    Entities/
    ValueObjects/
    Interfaces/

MyApplication.Application/
    Services/
    Commands/
    Queries/
    DTOs/

MyApplication.Infrastructure/
    Persistence/
    Repositories/
    Messaging/
    ExternalServices/

MyApplication.Web/
    Controllers/
    Middleware/
    Configuration/

The Web and Infrastructure projects can reference the inner projects as required, while the Domain project should remain independent from those outer implementation details.

Testing Onion Architecture

One of the practical benefits of protecting the domain from infrastructure concerns is that important business rules can be tested without starting the entire application.

[Fact]
public void CancelOrder_ShouldFail_WhenOrderIsAlreadyCompleted()
{
    var order = new Order();

    order.MarkAsCompleted();

    Assert.Throws<InvalidOperationException>(
        () => order.Cancel());
}

This type of test focuses on a domain rule rather than database, HTTP, or infrastructure behavior.

Common Mistakes

Putting Database Code in the Domain

The domain should not directly depend on a database provider or ORM. Database implementations belong outside the core.

Creating Interfaces for Everything

Abstractions should exist where they provide meaningful architectural value. Creating an interface for every class can add unnecessary complexity.

Breaking the Dependency Rule

Allowing the domain or application core to reference infrastructure libraries weakens one of the main benefits of the architecture.

Treating Projects as the Architecture

Having separate folders or projects does not guarantee correct dependency direction. The actual references and responsibilities matter more than project names.

Best Practices for Onion Architecture

  1. Keep domain logic independent from frameworks and infrastructure.
  2. Make dependency direction point toward the core.
  3. Define abstractions in inner layers when the inner logic requires infrastructure capabilities.
  4. Keep database and external integration implementations in outer layers.
  5. Keep the domain model focused on meaningful business concepts and rules.
  6. Use abstractions deliberately rather than creating unnecessary interfaces.
  7. Test business rules independently from infrastructure whenever practical.
  8. Keep architectural boundaries visible and understandable to the team.

When Should You Use Onion Architecture?

Onion Architecture can be useful when business logic is important and the application is expected to evolve over time. It is particularly helpful when the team wants to reduce the influence of frameworks, databases, and external services on the core of the application.

  • Complex business applications
  • Systems with significant domain rules
  • Applications expected to evolve for several years
  • Projects where automated testing is important
  • Applications where infrastructure technologies may change
  • Enterprise systems with strong maintainability requirements

For a very small CRUD application, the additional structure may not provide enough value to justify the extra abstractions.

Frequently Asked Questions

What is the main principle of Onion Architecture?

The main principle is that dependencies should point inward toward the core business logic, keeping inner layers independent from outer infrastructure and delivery concerns.

What is at the center of Onion Architecture?

The domain model and core business rules are placed at the center of the architecture.

Does Onion Architecture require multiple projects?

No. Multiple projects can help enforce boundaries in some implementations, but Onion Architecture is fundamentally about responsibilities and dependency direction rather than a required project layout.

Is Onion Architecture the same as Clean Architecture?

They share several important ideas, especially dependency inversion, separation of concerns, and protecting core business logic from infrastructure details. They are related architectural approaches, but their terminology and organization can differ between implementations.

Can Onion Architecture be used with ASP.NET Core?

Yes. ASP.NET Core applications can use Onion Architecture by keeping the domain and application logic separated from web, database, messaging, and other infrastructure concerns.

Interview Questions

  1. What is Onion Architecture?
  2. Why is Onion Architecture called an onion?
  3. What is the dependency rule in Onion Architecture?
  4. What belongs in the domain layer?
  5. What is dependency inversion and how is it used in Onion Architecture?
  6. Why should the domain layer not depend on the database?
  7. What are the benefits of Onion Architecture?
  8. What are the disadvantages of Onion Architecture?
  9. What is the difference between Onion Architecture and Layered Architecture?
  10. Is Onion Architecture suitable for every application?

Summary

Onion Architecture organizes a software system around a central domain model and places infrastructure and delivery concerns on the outside. Its defining rule is that dependencies should point inward toward the core rather than allowing business logic to depend directly on technical infrastructure.

By separating business rules from databases, frameworks, messaging systems, and external services, Onion Architecture can improve maintainability, testability, and the ability to replace infrastructure implementations.

The architecture adds useful structure for complex applications, but it should be applied deliberately. Small applications may not need the additional abstractions and boundaries.

Pro Tip

Protect the domain first. If changing your database, web framework, or external service forces major changes to core business rules, the dependency direction may not be serving the architecture well.

More Software Architecture lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.