-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodule.go
40 lines (32 loc) · 977 Bytes
/
module.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
// Package module provides a way to do dependency injection, with type-safe, without performance penalty.
// See [examples_test.go](./examples_test.go) for the basic usage.
package module
import (
"context"
"reflect"
)
type moduleKey string
// Module provides a module to inject and retreive an instance with its type.
type Module[T any] struct {
moduleKey moduleKey
}
// New creates a new module with type `T` and the constructor `builder`.
func New[T any]() Module[T] {
var t T
return Module[T]{
moduleKey: moduleKey(reflect.TypeOf(&t).Elem().String()),
}
}
// Value returns an instance of T which is injected to the context.
func (m Module[T]) Value(ctx context.Context) T {
var null T
v := ctx.Value(m.moduleKey)
if v == nil {
return null
}
return v.(T)
}
// With returns a new context instance which is injected a new instance `t`.
func (m Module[T]) With(ctx context.Context, t T) context.Context {
return context.WithValue(ctx, m.moduleKey, t)
}