Typorithm · medium

Onion Architecture

onion-architecturearchitecturedomain-centerinward-dependenciesinterfaces
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Onion Architecture

0%

Layered & Clean

Onion architecture arranges code in concentric rings with the domain at the center. All dependencies point inward, so infrastructure depends on the domain and never the reverse — the core defines interfaces the outer rings implement.

Picture concentric rings: the domain model sits in the center, surrounded by application services, then infrastructure and frameworks on the outside.

The inward dependency rule says source code dependencies may only point toward the center — outer rings know about inner rings, but the domain knows nothing about the outside.

The domain declares interfaces like UserRepository for what it needs; the outer infrastructure ring implements them, so the database can change without touching the core.

01

The domain model is the center of the onion.

02

All dependencies point inward toward the domain.

03

Infrastructure depends on the domain, never the reverse.

// domain layer — center of the onion
class User {
  constructor(public id: string, public email: string) {}
}

interface UserRepository {
  findById(id: string): User | null;
}

// infrastructure depends inward on the domain interface
class SqlUserRepository implements UserRepository {
  findById(id: string): User | null {
    return db.users.get(id);
  }
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Domain entity at the center

The User entity sits at the core of the onion; it knows nothing about storage or frameworks.

class User {

2. Interface owned by the domain

The repository interface is declared in the domain layer, so the domain defines its own needs.

interface UserRepository {

3. Infrastructure implements it

Infrastructure implements the domain's interface — it depends inward, never the reverse.

class SqlUserRepository implements UserRepository {

4. Database detail stays outside

The database call lives in the outer ring; the domain never sees it.

return db.users.get(id);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Onion Architecture: Lesson & Practice · Typorithm | ApplyDjinn