项目作者: mix-go

项目描述 :
DI, IoC container
高级语言: Go
项目地址: git://github.com/mix-go/xdi.git
创建时间: 2021-03-10T09:26:32Z
项目社区:https://github.com/mix-go/xdi

开源协议:Apache License 2.0

下载


Produced by OpenMix: https://openmix.org

Mix XDI

DI, IoC container

Overview

A library for creating objects and managing their dependencies. This library can be used for managing dependencies in a unified way, managing global objects, and refreshing dynamic configurations.

Installation

  1. go get github.com/mix-go/xdi

Quick start

Create a singleton through dependency configuration

  1. package main
  2. import (
  3. "github.com/mix-go/xdi"
  4. )
  5. type Foo struct {
  6. }
  7. func init() {
  8. obj := &xdi.Object{
  9. Name: "foo",
  10. New: func() (interface{}, error) {
  11. i := &Foo{}
  12. return i, nil
  13. },
  14. }
  15. if err := xdi.Provide(obj); err != nil {
  16. panic(err)
  17. }
  18. }
  19. func main() {
  20. var foo *Foo
  21. if err := xdi.Populate("foo", &foo); err != nil {
  22. panic(err)
  23. }
  24. // use foo
  25. }

Reference

Refer to another dependency configuration instance in the dependency configuration

  1. package main
  2. import (
  3. "github.com/mix-go/xdi"
  4. )
  5. type Foo struct {
  6. Bar *Bar
  7. }
  8. type Bar struct {
  9. }
  10. func init() {
  11. objs := []*xdi.Object{
  12. {
  13. Name: "foo",
  14. New: func() (interface{}, error) {
  15. // reference bar
  16. var bar *Bar
  17. if err := xdi.Populate("bar", &bar); err != nil {
  18. return nil, err
  19. }
  20. i := &Foo{
  21. Bar: bar,
  22. }
  23. return i, nil
  24. },
  25. },
  26. {
  27. Name: "bar",
  28. New: func() (interface{}, error) {
  29. i := &Bar{}
  30. return i, nil
  31. },
  32. NewEverytime: true,
  33. },
  34. }
  35. if err := xdi.Provide(objs...); err != nil {
  36. panic(err)
  37. }
  38. }
  39. func main() {
  40. var foo *Foo
  41. if err := xdi.Populate("foo", &foo); err != nil {
  42. panic(err)
  43. }
  44. // use foo
  45. }

Refresh singleton

When the configuration information changes during program execution, Refresh() can refresh the singleton instance to switch to using the new configuration. It is commonly used in microservice configuration centers.

  1. obj, err := xdi.DefaultContainer.Object("foo")
  2. if err != nil {
  3. panic(err)
  4. }
  5. if err := obj.Refresh(); err != nil {
  6. panic(err)
  7. }

License

Apache License Version 2.0, http://www.apache.org/licenses/