Skip to Content
Course content

101: Dependency Injection Without a Framework in Go

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think about a professional coffee machine. If the manufacturer hard-wired the machine to only accept one specific brand of coffee beans from one specific farm in Ethiopia, the machine would be useless the moment that farm went out of business or you decided you preferred a Colombian roast. To make the machine flexible, the engineers gave it a hopper. The hopper doesn't care who grew the beans; it just cares that the beans are the right size and shape. By providing a "slot" for the beans, the machine is now decoupled from the source.

In Go, Dependency Injection (DI) is exactly that hopper. Instead of a struct creating its own dependencies (hard-wiring the beans), you design the struct to accept those dependencies from the outside (the hopper). When people talk about "DI Frameworks," they're usually talking about complex tools that automate this, but in Go, we generally don't need them. All you need is a constructor and an interface.

The Trap of the Hard-Coded Database

I've seen this mistake in almost every junior dev's first Go project. They create a service and instantiate the database client right inside the constructor. It looks like this:

type UserService struct {
    db *PostgresClient
}

func NewUserService() *UserService {
    // This is the "hard-wired" mistake. 
    // The service is now stuck with Postgres forever.
    return &UserService{
        db: NewPostgresClient("conn_string"),
    }
}

The problem here is obvious: you can't test this UserService without a running Postgres database. Your tests will be slow, flaky, and require a Docker container just to check if a user's email is valid. You've tied your business logic to your infrastructure.

Defining the Contract

To fix this, we move from concrete types to interfaces. We define what the UserService needs, not what it is. This is our "bean specification."

// UserStore defines the behavior we need.
type UserStore interface {
    GetUser(id string) (*User, error)
}

type UserService struct {
    store UserStore // Note: we use the interface, not the concrete PostgresClient
}

// NewUserService now "injects" the dependency via the constructor.
func NewUserService(s UserStore) *UserService {
    return &UserService{
        store: s,
    }
}

Now, UserService doesn't know or care if it's talking to Postgres, MongoDB, or a hard-coded map in memory. It just knows that whatever it was given has a GetUser method.

Swapping Implementations for Testing

This is where the magic happens. Since we're using an interface, we can create a "Mock" store for our tests. I personally find this to be the single biggest productivity boost in Go development because your unit tests can run in milliseconds.

type MockUserStore struct {
    mockUser *User
}

func (m *MockUserStore) GetUser(id string) (*User, error) {
    return m.mockUser, nil
}

func TestUserService_GetUserName(t *testing.T) {
    // We inject the mock instead of a real database
    mock := &MockUserStore{mockUser: &User{Name: "Jane Doe"}}
    service := NewUserService(mock)

    name, _ := service.GetUserName("123")
    if name != "Jane Doe" {
        t.Errorf("Expected Jane Doe, got %s", name)
    }
}

In your main.go, you'll do the actual wiring. You create the real Postgres client and pass it into the service. You've effectively moved the "decision" of which database to use to the very top level of your application, leaving your business logic clean and agnostic.




📋 Practical Task

Refactoring the Notification Dispatcher

You've been handed a piece of code for a NotificationService that is currently hard-coded to use a specific SendGridEmailClient. This is making the tests fail because the CI environment doesn't have an API key for SendGrid.

Your Task:

  • Create a Notifier interface that defines a Send(message string) error method.
  • Modify the NotificationService struct to use the Notifier interface instead of the concrete SendGridEmailClient.
  • Update the NewNotificationService constructor to accept a Notifier as an argument.
  • Implement a MockNotifier struct that simply records if a message was sent, and use it to write a test that verifies the service calls the Send method correctly without actually sending an email.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.