Hacker News new | past | comments | ask | show | jobs | submit login

"Injection" in "dependency injection" simply refers to getting your dependencies from outside instead of building them yourself.

Let's take the case of an object which represents a simple CRUD web service that needs to talk to a database to get some data. Here is what it looks like without dependency injection:

  func NewService(databaseHostname, databaseLoginSecret string) (WebService, error) {
    databaseConn, err := databse.NewConn(databaseHostname, databaseLoginSecret)
    if err != nil {
        return WebService{}, fmt.Errorf("Failed to create database conn for WebService: %w", err)
    }
    return WebService{
        databaseConn: databaseConn
    }, nil
  }
And here is what it looks like with dependncy injection:

  func NewService(databaseConn DatabaseConn) WebService {
    return WebService{
        databaseConn: databaseConn
    }
  }
This is the only concept: don't build your own dependencies, get them from outside.

Ideally then there is a place in your application, possibly in `main()`, where all of the base services are initialized, in the required order, and references are passed between them as needed. This can include "factory" style objects if some of these need to be initialized on-demand.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: