-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
74 lines (61 loc) · 1.66 KB
/
main.go
File metadata and controls
74 lines (61 loc) · 1.66 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
package main
import (
"fmt"
"log"
"github.com/zignd/depot"
)
type Config struct {
DatabaseURL string
}
type Logger struct {
Prefix string
}
type Database struct {
Config Config
Logger Logger
}
type Service struct {
DB *Database
}
func main() {
fmt.Println("=== Example: Batch Error Checking ===")
fmt.Println()
// Create a new depot
dp := depot.New(depot.Config{LazyMode: true})
// Register multiple dependencies using RegisterMany
// This is cleaner than individual registrations
dp.RegisterMany(
depot.Singleton(func() Config {
return Config{DatabaseURL: "postgres://localhost/mydb"}
}),
depot.Singleton(func(c Config) Logger {
return Logger{Prefix: fmt.Sprintf("[%s]", c.DatabaseURL)}
}),
depot.Singleton(func(c Config, l Logger) *Database {
return &Database{Config: c, Logger: l}
}),
// Intentionally register an invalid dependency to show error tracking
depot.Singleton(nil), // This will error
depot.Singleton(func(db *Database) *Service {
return &Service{DB: db}
}),
)
// Check all registration errors at once
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")
}
// If we get here, all registrations succeeded
fmt.Println("All registrations successful!")
// Resolve a dependency
service, err := depot.Get[*Service](dp)
if err != nil {
log.Fatalf("Failed to resolve Service: %v", err)
}
fmt.Printf("\nService resolved successfully!\n")
fmt.Printf("Database URL: %s\n", service.DB.Config.DatabaseURL)
fmt.Printf("Logger Prefix: %s\n", service.DB.Logger.Prefix)
}