-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
161 lines (130 loc) · 3.82 KB
/
main.go
File metadata and controls
161 lines (130 loc) · 3.82 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package main
import (
"fmt"
"log"
"github.com/zignd/depot"
)
type Config struct {
DatabaseURL string
AppName string
}
type Logger struct {
Prefix string
}
func (l *Logger) Close() error {
fmt.Printf("%s Logger closed\n", l.Prefix)
return nil
}
type Database struct {
Config Config
Logger *Logger
}
func (db *Database) Close() error {
db.Logger.Prefix = fmt.Sprintf("%s [CLOSING]", db.Logger.Prefix)
fmt.Println("Database connection closed")
return nil
}
type CacheService struct {
Name string
}
type NotificationService struct {
Logger *Logger
}
type OrderService struct {
DB *Database
Cache *CacheService
}
type UserService struct {
DB *Database
Cache *CacheService
Notification *NotificationService
}
func main() {
fmt.Println("=== Example: RegisterMany ===")
fmt.Println()
// Create a new depot
dp := depot.New(depot.Config{LazyMode: true})
// Register all dependencies in a single call using RegisterMany
// This is cleaner and more readable than individual registrations
err := dp.RegisterMany(
// Configuration
depot.Singleton(func() Config {
return Config{
DatabaseURL: "postgres://localhost:5432/mydb",
AppName: "MyApp",
}
}),
// Logger
depot.Singleton(func(c Config) *Logger {
return &Logger{Prefix: fmt.Sprintf("[%s]", c.AppName)}
}),
// Database
depot.Singleton(func(c Config, l *Logger) (*Database, error) {
fmt.Println("Creating database connection...")
return &Database{Config: c, Logger: l}, nil
}),
// Cache Service (pre-created instance)
depot.Instance(&CacheService{Name: "Redis"}),
// Notification Service
depot.Singleton(func(l *Logger) *NotificationService {
return &NotificationService{Logger: l}
}),
// Named services
depot.SingletonNamed("orderService", func(db *Database, cache *CacheService) *OrderService {
return &OrderService{DB: db, Cache: cache}
}),
depot.SingletonNamed("userService", func(db *Database, cache *CacheService, notif *NotificationService) *UserService {
return &UserService{DB: db, Cache: cache, Notification: notif}
}),
// Transient service (new instance each time)
depot.TransientNamed("requestID", func() string {
return fmt.Sprintf("req-%d", len("random"))
}),
)
// Check all registration errors at once
if err != nil {
log.Printf("First error: %v\n", err)
}
if errs := dp.Errors(); errs != nil {
fmt.Println("Registration errors found:")
for i, err := range errs {
fmt.Printf(" %d. %v\n", i+1, err)
}
log.Fatal("Cannot proceed due to registration errors")
}
fmt.Println("All registrations successful!")
fmt.Println()
// Resolve named dependencies
orderService, err := depot.GetByName[*OrderService](dp, "orderService")
if err != nil {
log.Fatalf("Failed to resolve OrderService: %v", err)
}
userService, err := depot.GetByName[*UserService](dp, "userService")
if err != nil {
log.Fatalf("Failed to resolve UserService: %v", err)
}
fmt.Println("Services resolved successfully!")
fmt.Printf("Order Service - Database URL: %s, Cache: %s\n",
orderService.DB.Config.DatabaseURL,
orderService.Cache.Name)
fmt.Printf("User Service - Database URL: %s, Cache: %s\n",
userService.DB.Config.DatabaseURL,
userService.Cache.Name)
fmt.Println()
// Verify singleton behavior (same database instance)
if orderService.DB == userService.DB {
fmt.Println("✓ Both services share the same database instance (singleton)")
}
// Verify transient behavior
requestID1, _ := depot.GetByName[string](dp, "requestID")
requestID2, _ := depot.GetByName[string](dp, "requestID")
fmt.Printf("Request ID 1: %s\n", requestID1)
fmt.Printf("Request ID 2: %s\n", requestID2)
fmt.Println()
// Cleanup
fmt.Println("Shutting down...")
if err := dp.Shutdown(); err != nil {
log.Fatalf("Shutdown failed: %v", err)
}
fmt.Println("✓ Shutdown completed successfully")
}