Approach for dependency injection

Hi there,

I hope this is not against the forum rules. If so, I am sorry - Just delete this topic :slight_smile:

I just wrote about my chosen dependency injection approach: https://github.com/marczahn/pragmatic-dependency-injection-in-go

Maybe it helps someone. And of course I would be happy about critizism or comments about it :slight_smile:

1 Like

This looks like a carefully crafted approach. I love how it avoids runtime type checking and reflection.

I still prefer using the standard interface-based approach as long as I have no sophisticated requirements to address.

In this approach, an interface defines the desired behavior, and structs can implement this interface in their own way.

Functions then can accept the interface type, and callers can pass any struct that implements the interface.

Here is an example of a database interface and two structs, realDB and mockDB that implement the database interface. Function doSomething() accepts a database and therefore works fine with either a realDB or a mockDB variable passed into it.

This is a really simple standard Go idiom.

(Warning: The following code is over-simplified and does not run, let alone do something meaningful. It just serves to illustrate the concept in a concise way.)

type database interface {
    Query()
    Update()
}

type realDB struct{...}

func (db *realDB) Query() ... { 
    ... 
}

func (db *realDB) Update() ... { 
    ... 
}

type mockDB struct{...}

func (db *mockDB) Query() ... { 
    ... 
}

func (db *mockDB) Update() ... { 
    ... 
}

// doSomething accepts any struct that implements
// the database interface
func doSomething(db *database) {
    db.Query()
}

func main() {
    r = &realDB{}
    doSomething(r)
	
    m := &mockDB{}
    doSomething(m)
}
```
1 Like

Hi Christoph,

If I understand you correctly you want to use interfaces for defining dependencies instead of structs. If I get this correctly: You are absolutely right. This is even better - I just wanted to show examples. Since using interfaces instead of implementations I will change this - It shows even more this advantage of DI.

Thank you very much for this remark!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.