-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
82 lines (64 loc) · 1.64 KB
/
Copy pathmain.go
File metadata and controls
82 lines (64 loc) · 1.64 KB
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
package main
import (
"context"
"fmt"
"github.com/danpasecinic/needle"
)
type Config struct {
DatabaseURL string
Port int
}
type Database struct {
URL string
}
func NewDatabase(cfg *Config) *Database {
return &Database{URL: cfg.DatabaseURL}
}
type UserRepository struct {
db *Database
}
func NewUserRepository(db *Database) *UserRepository {
return &UserRepository{db: db}
}
func (r *UserRepository) FindByID(id int) string {
return fmt.Sprintf("User %d from %s", id, r.db.URL)
}
type UserService struct {
repo *UserRepository
}
func NewUserService(repo *UserRepository) *UserService {
return &UserService{repo: repo}
}
func (s *UserService) GetUser(id int) string {
return s.repo.FindByID(id)
}
func main() {
c := needle.New()
_ = needle.Register(c, needle.SpecValue(&Config{
DatabaseURL: "postgres://localhost/mydb",
Port: 8080,
}))
_ = needle.Register(c, needle.Spec[*Database]{
Provider: func(ctx context.Context, c *needle.Container) (*Database, error) {
cfg := needle.MustInvoke[*Config](c)
return NewDatabase(cfg), nil
},
})
_ = needle.Register(c, needle.Spec[*UserRepository]{
Provider: func(ctx context.Context, c *needle.Container) (*UserRepository, error) {
db := needle.MustInvoke[*Database](c)
return NewUserRepository(db), nil
},
})
_ = needle.Register(c, needle.Spec[*UserService]{
Provider: func(ctx context.Context, c *needle.Container) (*UserService, error) {
repo := needle.MustInvoke[*UserRepository](c)
return NewUserService(repo), nil
},
})
if err := c.Validate(); err != nil {
panic(err)
}
svc := needle.MustInvoke[*UserService](c)
fmt.Println(svc.GetUser(42))
}