Dependency Injection in GO lang

Dependency Injection (DI):

DI is a design pattern used to remove dependencies between software components by injecting required dependencies into an object from outside the object itself. In other words, DI is a technique that allows us to remove the dependency of one class on another by inverting the control of the dependencies from the calling class to the dependency injector. DI can be done manually, but most modern programming languages have frameworks that automate the process of injecting dependencies. The goal of DI is to achieve loose coupling between classes, which results in code that is more modular, flexible, and easier to test.

Example of how to use dependency injection (DI) in Go:

package main

import "fmt"

type Database interface {
    Query(query string) string

type MySQL struct {}

func (m MySQL) Query(query string) string {
    return "MySQL: " + query

type PostgreSQL struct {}

func (p PostgreSQL) Query(query string) string {
    return "PostgreSQL: " + query

type User struct {
    db Database

func (u User) Get() string {
    return u.db.Query("SELECT * FROM users")

func main() {
    mysql := MySQL{}
    user := User{db: mysql}

    postgres := PostgreSQL{}
    user = User{db: postgres}

In this example, we define an interface called Database that has a single method called Query. We then define two structs called MySQL and PostgreSQL that implement the Database interface.

We then define a struct called User that has a single field of type Database. We also define a method called Get on the User struct that uses the db field to execute a SQL query.

In the main function, we create an instance of the MySQL struct and use it to create an instance of the User struct. We then call the Get method on the User struct and print the result.

We then repeat the process with an instance of the PostgreSQL struct, showing how we can easily swap out one implementation of the Database interface for another using dependency injection.

Note that this is just a simple example of how dependency injection can be used in Go, and there are many other ways to implement DI depending on your specific needs and requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *

72 + = 74

Related Post