Search Sreeni's Insights

Filter by content type
technical February 19, 2015 7 min read

Onion architecture vs N-Tier - which one to choose?

Onion architecture and N-Tier compared through dependency direction, project structure, domain boundaries, dependency injection, and criteria for choosing between them.

Share:

Onion architecture vs N-Tier - which one to choose?

Architecture is not only about the number of projects in a solution. It is about which part is allowed to depend on which other part, and how easily the system is changing when a business rule changes. N-Tier often organizes code from presentation to data, while Onion architecture is turning the dependency direction toward the domain.

In this article, we are going to see the difference between N-Tier and Onion architecture, use a worked fund-domain example, and make a pragmatic choice based on domain complexity and team needs.

TL;DR Summary

  • N-Tier usually organizes responsibilities from the user interface toward infrastructure.
  • Onion architecture keeps the domain and application rules at the centre.
  • The dependency direction in Onion points inward, so infrastructure implements core abstractions.
  • Onion can improve testability but introduces more interfaces and mapping.
  • N-Tier is often enough for simple CRUD applications with modest business rules.
  • Choose based on change pressure, domain complexity and team maturity, not architecture fashion.

Challenges

Dependency direction

When the business project references Entity Framework models and ASP.NET types, infrastructure decisions leak into business rules. Replacing a data store becomes a large change even when the business behaviour is unchanged. The dependency graph is a blind spot because the project names may still look clean.

Over-engineering

An Onion design can add interfaces, adapters and dependency injection configuration before the application has a meaningful rule. The team spends time wiring abstractions instead of learning the domain. This is a trade-off, and we should pay it only when it removes real coupling.

Test feedback

A business rule which requires a database and web request for every test gives slow feedback. A domain-centred design can test the rule in memory. But testability also depends on good boundaries and test design, not on the word Onion in the architecture document.

What is N-Tier?

N-Tier separates presentation, business and data access responsibilities into tiers which commonly depend downward.

In simple terms, the web layer calls the business layer, and the business layer calls the data layer. This is easy for many teams to understand and works well when persistence is a stable implementation detail. Refer the “What is N-Tier architecture and where does it fail?” article for failure cases.

What is Onion architecture?

Onion architecture structures the application around a central domain model, with dependencies pointing from outer infrastructure toward inner application and domain layers.

In simple terms, the centre contains business rules and does not know about SQL, Entity Framework or ASP.NET. The outer layer provides adapters such as repositories, controllers and messaging. It is similar to an onion: the outer layers can be replaced while the centre remains focused on the business.

Why the domain centre is important?

Consider a fund application. “A unit transaction cannot be accepted after the valuation date is closed” is a domain rule. It should remain true whether the input came from MVC, a batch process or a message. If this rule exists only in a controller, another entry point can bypass it.

The following diagram depicts the dependency direction in the two approaches,

Onion architecture and N-Tier dependency direction
Onion architecture and N-Tier dependency direction

Onion architecture structure

Domain layer

The domain layer contains entities, value objects and business rules. It should use ordinary C# types and avoid persistence annotations when those annotations are not business concepts. This keeps tests fast and prevents the data store from deciding the model.

Application layer

The application layer coordinates use cases. It can load a fund, ask the domain to apply a rule and request persistence through an abstraction. It should not become a second domain layer containing every rule in procedural services.

Infrastructure layer

Infrastructure implements interfaces required by the inner layers, such as an Entity Framework 6 repository or an email sender. Dependency injection composes the concrete implementation at the application boundary. The centre does not need to know which provider is used.

Presentation layer

The MVC controller or Web API controller translates HTTP into an application command and translates the result into a response. It should not contain the rule for valuation dates, because a background process may need the same rule.

Worked project layout and code

Find below one possible solution layout,

Funds.Domain
  Entities/Fund.cs
  Interfaces/IFundRepository.cs
Funds.Application
  Services/FundService.cs
Funds.Infrastructure
  Persistence/EfFundRepository.cs
  Persistence/FundsDbContext.cs
Funds.Web
  Controllers/FundsController.cs
  App_Start/DependencyConfig.cs

The interface is staying in the inner layer,

namespace Funds.Domain.Interfaces
{
    public interface IFundRepository
    {
        Fund Find(int id);
        void Save(Fund fund);
    }
}

The application service is using the interface, it is not knowing Entity Framework,

public sealed class FundService
{
    private readonly IFundRepository repository;

    public FundService(IFundRepository repository)
    {
        this.repository = repository;
    }

    public void CloseFund(int fundId)
    {
        Fund fund = repository.Find(fundId);
        if (fund == null)
            throw new InvalidOperationException("Fund was not found");
        fund.Close();
        repository.Save(fund);
    }
}

Infrastructure is implementing the interface,

public sealed class EfFundRepository : IFundRepository
{
    private readonly FundsDbContext context;

    public EfFundRepository(FundsDbContext context)
    {
        this.context = context;
    }

    public Fund Find(int id)
    {
        return context.Funds.SingleOrDefault(x => x.Id == id);
    }

    public void Save(Fund fund)
    {
        context.SaveChanges();
    }
}

At the composition root, Unity is wiring the outer implementation to the inner abstraction,

container.RegisterType<FundsDbContext>(
    new PerRequestLifetimeManager());
container.RegisterType<IFundRepository, EfFundRepository>();
container.RegisterType<FundService>();

It means the domain is not having a reference to Web or EF, and we can replace infrastructure in a test. This is the main benefit of Onion, not merely the presence of four projects.

Where the Onion approach is failing?

The application layer can become a second BLL with no domain behaviour, the interfaces can be created for every class, and the mapping code can be more than the business logic. As a result of this, a simple CRUD screen is taking more time without removing a real dependency. We should keep the centre meaningful and introduce an abstraction when a change, test or second implementation is requiring it.

The trade-off is depending on context. For a simple article administration screen, N-Tier with a clear service and repository is sufficient. For a fund domain with rules which are shared by MVC, Web API and batch jobs, Onion is helping us keep those rules in one place. Start small, otherwise architecture is becoming technical debt of its own.

When the domain rule is spread across controllers, we are reacting to each new entry point and finding the defect after release. Keeping the rule at the centre lets us be proactive and test it before MVC or batch traffic is reaching the customer. The trade-off is more wiring, hence in our case Onion is selected only for domains having real behaviour and multiple adapters.

Which one should we choose?

ContextRecommended starting pointReason
Simple CRUD with few rulesN-Tier or a modular single applicationLess ceremony and faster delivery
Complex domain with many rulesOnion or domain-centred structureProtects rules from infrastructure change
Multiple entry pointsOnion or explicit application servicesPrevents one adapter owning the rules
Team unfamiliar with dependency inversionStart with clear N-Tier boundariesLearn the domain before adding abstractions

Do not create an interface for every class without a reason. Add a boundary when a dependency changes independently, is difficult to test, or has more than one implementation. If the domain is simple, the best of both worlds may be a modest N-Tier application with business rules kept out of controllers.

The architecture should also make the onboarding path clear. A developer should be able to follow one request from the controller to the use case and then to the infrastructure adapter without guessing where a rule is hidden. If the dependency direction is correct but the flow is difficult to explain, the design still needs refinement.

Wrap up

In this article, we have looked at N-Tier, Onion architecture, dependency direction, project layout, DI wiring, the domain centre and selection criteria. I appreciate your time and efforts to read this article. In the next article, I will walk you through Repository and Unit of Work patterns with Entity Framework.

Related Posts