Dependency Injection for Go with facebookgo-inject

November 9th, 2016 by

Setting up a larger application using dependency injection always requires us developers to set up our application’s object graph.

Programming in Go there is a library that eases this task for us, offering a reflect based injector to set up the graph in a few steps, named facebookgo-inject.

In the following article I’d like to demonstrate dependency injection using this library for a small sample application.

Go dependency injection with facebookgo

Go dependency injection with facebookgo

 

Dependency Injection Example

First of all we need to fetch the dependency for facebookgo-inject (thanks @bborbe for showing me this library! :))

$ go get github.com/facebookgo/inject

This is our sample application – as we can see, our BookService gets the dependencies for Database and Validator injected.

package main
 
import (
	"log"
 
	"github.com/facebookgo/inject"
)
 
type Book struct {
	title string
}
 
type BookService struct {
	database  Database  `inject:""`
	validator Validator `inject:""`
}
 
func (s *BookService) create(book Book) {
	log.Printf("creating new book entity: %v\n", book)
	if s.validator.validate(book) {
		s.database.save(book)
	}
}
 
type Database struct {
}
 
func (db *Database) save(entity interface{}) {
	log.Printf("saving entity to database: %v", entity)
}
 
type Validator struct {
}
 
func (v *Validator) validate(entity interface{}) bool {
	log.Printf("validating entity: %v", entity)
	return true
}
 
func main() {
	log.Println("starting injection example")
	var graph inject.Graph
	var service BookService
	graph.Provide(
		&inject.Object{Value: &service},
		&inject.Object{Value: Database{}},
		&inject.Object{Value: Validator{}}
	)
	graph.Populate()
 
	log.Println("listing known objects..")
	for _, obj := range graph.Objects() {
		log.Printf("object known: %v\n", obj)
	}
 
	service.create(Book{title: "Some book"})
}

Running the Example

We may now run our sample application in the command line like this:

$ go run example.go
2016/11/09 16:18:21 starting injection example
2016/11/09 16:18:21 listing known objects..
2016/11/09 16:18:21 object known: *main.BookService
2016/11/09 16:18:21 creating new book entity: {Some book}
2016/11/09 16:18:21 validating entity: {Some book}
2016/11/09 16:18:21 saving entity to database: {Some book}

Tutorial Sources

Please feel free to download the tutorial sources from my Bitbucket repository, fork it there or clone it using Git:

git clone https://bitbucket.org/hascode/facebookgo-inject-sample.git

Resources

Tags: , , , , , ,

Search
Categories