aboutsummaryrefslogtreecommitdiff
path: root/README.md
diff options
context:
space:
mode:
authorAlexander Kiryukhin <i@neonxp.dev>2022-07-17 02:51:22 +0300
committerAlexander Kiryukhin <i@neonxp.dev>2022-07-17 02:51:22 +0300
commit9d2403804cbe620f000792e22a4573e46d631fac (patch)
tree9b2e86aa50686802fed90f0851c3d8636b5f7496 /README.md
initial
Diffstat (limited to 'README.md')
-rw-r--r--README.md83
1 files changed, 83 insertions, 0 deletions
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..6a04eb8
--- /dev/null
+++ b/README.md
@@ -0,0 +1,83 @@
+# Go Dependency Inject Container
+
+Simple dependecy inject container with generics.
+
+Use for your own risk!
+
+## Usage
+
+### Register dependency
+
+```go
+di.Register("service id", func () (*Service, error) { /* construct service */ })
+```
+
+### Get dependency
+
+Get dependencies by type:
+
+```go
+services, err := di.Get[Service]()
+```
+
+Get dependencies by type and id:
+```go
+service, err := di.GetById[Service]("service id")
+```
+
+### Go doc
+
+```go
+package di // import "go.neonxp.dev/di"
+
+func Get[T any]() ([]*T, error)
+func GetById[T any](id string) (*T, error)
+func Register[T any](id string, constructor func() (*T, error))
+```
+
+### Example
+
+```go
+ di.Register("serviceA", func() (*ServiceA, error) { // <- Register service A
+ return &ServiceA{}, nil
+ })
+ di.Register("serviceB", func() (*ServiceB, error) { // <- Register service B, that depends from service A
+ serviceA, err := di.Get[ServiceA]() // <- Get dependency from container by type
+ if err != nil {
+ return nil, err
+ }
+
+ return &ServiceB{
+ ServiceA: serviceA[0],
+ }, nil
+ })
+
+// Do work ...
+service, err := di.GetById[ServiceB]("serviceB") // <- Get instantinated service B
+if err != nil {
+ panic(err)
+}
+
+service.DoStuff() // Output: Hello, world!
+
+
+// Services ...
+type ServiceA struct{}
+
+func (d *ServiceA) DoStuff() {
+ fmt.Println("Hello, world!")
+}
+
+type ServiceB struct {
+ ServiceA *ServiceA
+}
+
+func (d *ServiceB) DoStuff() {
+ d.ServiceA.DoStuff()
+}
+
+```
+
+## License
+
+GPLv3