-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
69 lines (57 loc) · 1.84 KB
/
main.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
package main
import (
"context"
"time"
"github.com/sirupsen/logrus"
"github.com/phramz/dimple"
)
// TimeServiceInterface it might be beneficial to have an interface for abstraction when it comes to service decoration
type TimeServiceInterface interface {
Now()
}
// OriginTimeService is the service we want to decorate
type OriginTimeService struct {
Logger *logrus.Logger `inject:"logger"`
Format string `inject:"config.time_format"`
}
func (t *OriginTimeService) Now() {
t.Logger.Infof("It is %s", time.Now().Format(t.Format))
}
// TimeServiceDecorator will decorate OriginTimeService
type TimeServiceDecorator struct {
Logger *logrus.Logger `inject:"logger"`
Decorated TimeServiceInterface
}
func (t *TimeServiceDecorator) Now() {
t.Logger.Infof("%d seconds elapsed since January 1, 1970 UTC", time.Now().Unix())
t.Decorated.Now() // let's call the origin TaggedService as well
}
func main() {
container := dimple.Builder(
dimple.Param("config.time_format", time.Kitchen),
dimple.Service("logger", dimple.WithInstance(logrus.New())),
dimple.Service("service.time", dimple.WithInstance(&OriginTimeService{})),
dimple.Decorator("service.time.decorator", "service.time", dimple.WithContextFn(func(ctx dimple.FactoryCtx) (any, error) {
return &TimeServiceDecorator{
// we can get the inner (origin) instance if we need to
Decorated: ctx.Decorated().(TimeServiceInterface),
}, nil
})),
).
MustBuild(context.Background())
go func() {
// now when we MustGet() the ServiceTime, we will actually receive the TimeServiceDecorator
timeService := dimple.MustGetT[TimeServiceInterface](container, "service.time")
for {
select {
case <-container.Ctx().Done():
return
default:
// we will output the time every second
time.Sleep(time.Second)
timeService.Now()
}
}
}()
<-container.Ctx().Done()
}