-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
doc.go
84 lines (65 loc) · 1.82 KB
/
doc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
Package gocontainer is a simple dependency injection container
Take the following example:
First file `main.go` simply gets the repository from the container and prints it
we use **MustInvoke** method to simply present the way where we keep type safety
package main
import (
"github.com/vardius/gocontainer/example/repository"
"github.com/vardius/gocontainer"
)
func main() {
gocontainer.MustInvoke("repository.mysql", func(r Repository) {
fmt.Println(r)
})
}
Our database implementation uses `init()` function to register db service
package database
import (
"fmt"
"database/sql"
"github.com/vardius/gocontainer"
)
func NewDatabase() *sql.DB {
db, _ := sql.Open("mysql", "dsn")
return db
}
func init() {
db := gocontainer.MustGet("db")
gocontainer.Register("db", NewDatabase())
}
Our repository accesses earlier on registered db service
and following the same patter uses `init()` function to register repository service within container
package repository
import (
"fmt"
"database/sql"
"github.com/vardius/gocontainer"
_ "github.com/vardius/gocontainer/example/database"
)
type Repository interface {}
func NewRepository(db *sql.DB) Repository {
return &mysqlRepository{db}
}
type mysqlRepository struct {
db *sql.DB
}
func init() {
db := gocontainer.MustGet("db")
gocontainer.Register("repository.mysql", NewRepository(db.(*sql.DB)))
}
You can disable global container instance by setting gocontainer.GlobalContainer to nil.
This package allows you to create many containers.
package main
import (
"github.com/vardius/gocontainer/example/repository"
"github.com/vardius/gocontainer"
)
func main() {
// disable global container instance
gocontainer.GlobalContainer = nil
mycontainer := gocontainer.New()
mycontainer.Register("test", 1)
}
*/
package gocontainer