CodeGym /행동 /Go SELF /DI by hand — `NewApp(deps...)` and assembly in `main`

DI by hand — `NewApp(deps...)` and assembly in `main`

Go SELF
레벨 28, 레슨 2
사용 가능

1. DI by hand and the assembly point

DI (Dependency Injection) sounds like we are about to build some kind of “enterprise architecture” and call in a dependency-container shaman. In Go, though, everything is much more down to earth: DI “by hand” means that you create dependencies outside and pass them explicitly into whatever is going to use them. Not “I spun up a database inside the function,” but “I created the implementation in main and handed it to the service.”

The most important idea: DI is not about pretty diagrams, but about controlling connections. When dependencies are created inside business logic, code becomes hard to test, hard to extend, and easy to accidentally “nail down” to a specific implementation. When dependencies are passed from the outside, it becomes clear who is responsible for what, and the compiler helps you keep the architecture in place instead of fighting it.

In Go, a dependency is not just a “database”

Beginners often think a dependency is something big and scary: a database, a network, queues. But in Go, a dependency is any thing your code “uses” but should not “create” inside itself. This can be a task store, an ID generator, a writer for output, a time source, config, and so on. The more honestly you admit this, the simpler the code becomes.

In our training application (a mini task tracker), we will treat at least the task store and the place where output is written as dependencies. And here is an immediately useful habit: if a function accepts context.Context, then all dependencies that do work (I/O, storage) should also accept ctx, so that cancellation/timeout can travel down the call chain.

A small “map” for orientation:

What it is Example Why it is a dependency
Storage
TaskStore
You can replace in-memory with file/DB without changing the scenario
Output
io.Writer
You can write to stdout, buffer, file — without rewriting the logic
Operation context
context.Context
Propagates cancellation/deadlines down the call stack

Why creating dependencies inside the logic is a trap

Let us start with an anti-example. It is very realistic: you are writing a function, it needs storage, and you think, “well, I’ll just do it quickly.”

package app

import "example.com/myapp/adapters/memstore"

func AddTaskBad(title string) {
	store := memstore.New() // ← dependency is created inside
	_ = store               // some logic follows...
}

The problem here is not that memstore is bad. The problem is that now your business logic “knows” a specific implementation and effectively says: “I can only work with memstore.” Want to store tasks in a file tomorrow? You will have to change the app layer. Want to test it? You will have to live with the fact that a fresh store is created every time inside. Want to reuse it? It becomes awkward.

DI “by hand” does the opposite: the app layer defines the contract (interface), and the implementation is created from the outside, usually in main.

Assembly point: one place where everything is wired together

The assembly point (composition root) is the place where the application is “assembled from parts”: concrete implementations are created, passed into constructors, a ready top-level object is obtained, and scenarios are started. In small programs, this is almost always main.

It sounds boring, but it genuinely makes life easier: you do not spread dependency creation across ten files. If something breaks later, you know where to look: in one place.

Here is the picture of how we want to think about our application:

flowchart TD
    main[main: assembly point] --> mem[adapters/memstore: concrete implementation]
    main --> app[app: scenarios/service]
    app --> domain[domain: model and rules]
    app -->|via interface| mem

The key point: app depends on the interface, and main supplies the implementation.

2. Minimal domain

Now we will not complicate the domain. What matters is that the domain is “clean”: data structure and rules. Suppose the rule is this: a task title must not be empty. That is already familiar error logic: a function either returns a result or an error. In Go this is the standard style, and it fits DI very well because everything becomes explicit and testable.

// domain/task.go
package domain

import "errors"

var ErrEmptyTitle = errors.New("empty title")

type Task struct {
	ID    int
	Title string
	Done  bool
}

And a small constructor:

// domain/new_task.go
package domain

func NewTask(id int, title string) (Task, error) {
	if title == "" {
		return Task{}, ErrEmptyTitle
	}
	return Task{ID: id, Title: title, Done: false}, nil
}

So far everything is simple: the domain knows nothing about fmt.Println, files, or CLI. It just holds the rule.

3. Storage contract in app

Now let us move to the heart of DI. We want the “add task” scenario to work with any storage as long as it supports the needed operations. Therefore the consumer declares the interface (the app layer), not the implementation.

// app/store.go
package app

import (
	"context"

	"example.com/myapp/domain"
)

type TaskStore interface {
	NextID(ctx context.Context) (int, error)
	Save(ctx context.Context, t domain.Task) error
}

Notice that app imports domain because it uses domain.Task. That is fine: scenarios know about the domain. But app does not import memstore — and that is the crucial part.

4. Application constructor NewApp

The most recognizable DI pattern in Go is constructors of the form NewX(...). Not because the language requires it, but because it helps create an object immediately in a valid state. We will make App — the top-level object of the app layer.

There are two common styles:

  • NewApp(store, out, ...) as parameters
  • NewApp(Deps{...}) via a deps structure

In educational projects and in real services, the second option is often more convenient because dependencies do not turn into an “argument sausage” when there are many of them.

Let us start with Deps.

// app/app.go
package app

import "io"

type Deps struct {
	Store TaskStore
	Out   io.Writer
}

type App struct {
	store TaskStore
	out   io.Writer
}

Now the constructor:

// app/new.go
package app

import (
	"errors"
	"io"
)

func NewApp(deps Deps) (*App, error) {
	if deps.Store == nil {
		return nil, errors.New("nil store")
	}
	if deps.Out == nil {
		deps.Out = io.Discard // safe default
	}
	return &App{store: deps.Store, out: deps.Out}, nil
}

Here DI looks as “Go-like” as possible: no magic, no reflection, no containers. Just parameters, checks, and a return value.

5. Scenarios in App

Now let us add the AddTask method. It accepts context.Context because storage operations can potentially be long-running, and because that is the standard form of a contract in Go code for operations.

// app/add_task.go
package app

import (
	"context"
	"fmt"

	"example.com/myapp/domain"
)

func (a *App) AddTask(ctx context.Context, title string) (domain.Task, error) {
	id, err := a.store.NextID(ctx)
	if err != nil {
		return domain.Task{}, fmt.Errorf("next id: %w", err)
	}
	return domain.NewTask(id, title)
}

We are not saving the task yet — let us add saving, but briefly:

// app/add_task_save.go
package app

import (
	"context"
	"fmt"

	"example.com/myapp/domain"
)

func (a *App) AddAndSave(ctx context.Context, title string) (domain.Task, error) {
	t, err := a.AddTask(ctx, title)
	if err != nil {
		return domain.Task{}, err
	}
	if err := a.store.Save(ctx, t); err != nil {
		return domain.Task{}, fmt.Errorf("save: %w", err)
	}
	return t, nil
}

Notice the characteristic thing: we do not create memstore.New() inside. We simply use a.store. That is DI.

6. The memstore adapter

Now let us write the simplest in-memory storage. It will live in adapters/memstore. Important: the adapter imports domain (it needs to store domain.Task), but it does not import app. It simply “matches” the interface by methods.

// adapters/memstore/store.go
package memstore

import (
	"context"

	"example.com/myapp/domain"
)

type Store struct {
	next int
	data map[int]domain.Task
}

Constructor:

// adapters/memstore/new.go
package memstore

func New() *Store {
	return &Store{next: 1, data: make(map[int]domain.Task)}
}

Methods:

// adapters/memstore/methods.go
package memstore

import "context"

func (s *Store) NextID(ctx context.Context) (int, error) {
	id := s.next
	s.next++
	return id, nil
}
// adapters/memstore/save.go
package memstore

import (
	"context"

	"example.com/myapp/domain"
)

func (s *Store) Save(ctx context.Context, t domain.Task) error {
	s.data[t.ID] = t
	return nil
}

Yes, ctx is not used here yet. That is normal. The interface requires it — the implementation accepts it. Later there will be implementations where ctx really matters (for example, file or network storage), and you will not have to rewrite the entire contract.

7. Assembly in main

Now for the fun part: main is our assembly point. Here we create memstore.Store, choose out (let it be stdout), call NewApp, and get a ready application.

// main.go
package main

import (
	"context"
	"fmt"
	"os"

	"example.com/myapp/adapters/memstore"
	"example.com/myapp/app"
)

func main() {
	store := memstore.New()
	a, err := app.NewApp(app.Deps{Store: store, Out: os.Stdout})
	if err != nil {
		fmt.Println("init error:", err) // init error: nil store (if you forgot Store)
		return
	}

	t, err := a.AddAndSave(context.Background(), "learn DI in Go")
	if err != nil {
		fmt.Println("runtime error:", err)
		return
	}

	fmt.Fprintln(os.Stdout, "added task:", t.Title) // added task: learn DI in Go
}

It looks almost comically simple — and that is the strength of Go. DI is not a separate technology, but a discipline: “create outside, pass inside.”

8. Useful DI nuances

io.Writer as a dependency

Even if you are not writing tests yet, io.Writer as a dependency is a super technique for beginners: you stop “nailing down” printing to fmt.Println directly inside business logic. Instead, business logic writes to wherever it was told to write.

Let us add a simple method to “tell the user that the task was added.” This is not the domain; it is already a UX detail, so it is more logical to keep it at the App level or in an outer layer. But for a learning example, let us allow App to print to a.out.

// app/print.go
package app

import (
	"fmt"
)

func (a *App) PrintAdded(title string) {
	fmt.Fprintln(a.out, "ok:", title) // ok: learn DI in Go
}

And use it in main:

// main.go (fragment)
t, _ := a.AddAndSave(context.Background(), "learn DI in Go")
a.PrintAdded(t.Title) // ok: learn DI in Go

If tomorrow you want to write to a file — main changes, but app stays the same. That is “loose coupling” without the big words.

Why NewApp sometimes returns (*App, error)

It is easy for a beginner to get stuck: “Why is there an error here, but not there?” The pragmatic answer: the constructor returns an error if it can actually detect a bad configuration and it is important to stop immediately.

For example, Store == nil is almost guaranteed to become a future panic (or strange behavior), so it is better to fail early, at the assembly point. But Out == nil can be replaced with io.Discard and the program can continue.

If a constructor does not perform checks and always creates a valid value, it can simply return *App. But as soon as “required dependencies” appear, error becomes useful because you catch the problem before running scenarios.

Three micro-rules for DI by hand

DI can easily be taken to absurdity: you start passing 20 dependencies into every function and proudly call it architecture. But we need a healthy minimum. Let us agree on simple rules of behavior, without fanaticism.

  • First, dependencies are created by the assembly point. That is usually main, sometimes a separate assembly package, but in a learning project — main.
  • Second, the app layer should not import adapters: no import adapters/memstore inside app.
  • Third, the interface lives where it is used. If app uses storage, the TaskStore interface lives in app, and the implementation simply fits it.

If you keep these three rules in mind, DI stops being a “framework” and becomes just a style of writing code: calm and predictable.

9. Typical mistakes when doing DI by hand

Mistake #1: “I’ll make a global variable, and that will be DI.”
Global variables look like a convenient shortcut, but in practice they are a hidden dependency: it is unclear who sets them, when, and whether they can be changed. In the end you get code that depends on call order and “initialization magic,” not on explicit parameters.

Mistake #2: Creating the dependency implementation inside the scenario.
The most common problem: inside AddTask, memstore.New() or os.OpenFile(...) suddenly appears. This breaks the idea of layers: the scenario starts to know infrastructure details. It is better when the scenario knows only the interface, and the creation of the implementation stays in main.

Mistake #3: Making the interface “just in case huge.”
Beginners sometimes write a 15-method interface because “well, maybe we will need it.” As a result, it becomes harder to substitute the implementation, and you make your own life more difficult. In Go, interfaces are usually kept small: exactly as many methods as the current consumer needs.

Mistake #4: Not checking dependencies in NewApp and catching a panic later.
If Store is required, it is better to discover the problem immediately when assembling the application. Otherwise you will get an error somewhere in the middle of execution, and it will look like “for some reason everything is nil,” when in reality it is a configuration error.

Mistake #5: Passing dependencies “everywhere,” instead of passing one assembled object.
If in main you create store, out, cfg, and then start passing them into every function separately, the code quickly balloons. Often it is simpler to assemble App (or Service) once and then work with it as a single top-level object. That is the whole point of NewApp(deps...): wire everything together once, then live peacefully.

1
과제
Go SELF, 레벨 28, 레슨 2
잠금
말하는 로봇
말하는 로봇
1
과제
Go SELF, 레벨 28, 레슨 2
잠금
출입증 번호 카운터
출입증 번호 카운터
1
과제
Go SELF, 레벨 28, 레슨 2
잠금
DI에 대한 노트
DI에 대한 노트
1
과제
Go SELF, 레벨 28, 레슨 2
잠금
목록 일괄 가져오기
목록 일괄 가져오기
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION