Dependency injection

Dependency injection for Go programming language.

Dependency injection is one form of the broader technique of inversion of control. It is used to increase modularity of the program and make it extensible.

Examples

  1. type A struct {
  2. Name string
  3. }
  4. func NewA() *A {
  5. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  6. name := "A-" + strconv.Itoa(r.Int())
  7. return &A{Name: ls}
  8. }
  9. services := NewServiceCollection()
  10. services.AddSingleton(NewA)
  11. //serviceCollection.AddSingletonByImplementsAndName("redis-master", NewRedis, new(abstractions.IDataSource))
  12. //serviceCollection.AddTransientByImplements(NewRedisClient, new(redis.IClient))
  13. //serviceCollection.AddTransientByImplements(NewRedisHealthIndicator, new(health.Indicator))
  14. serviceProvider := services.Build()
  15. var env *A
  16. _ = serviceProvider.GetService(&env) // used

How will dependency injection help me?

Dependency injection is one form of the broader technique of inversion of control. It is used to increase modularity of the program and make it extensible.

Contents

Installing

  1. go get -u github.com/yoyofxteam/dependencyinjection@v1.0.0

Providing

To start, we will need to create two fundamental types: http.Server and http.ServeMux. Let’s create a simple constructors that initialize it:

  1. // NewServer creates a http server with provided mux as handler.
  2. func NewServer(mux *http.ServeMux) *http.Server {
  3. return &http.Server{
  4. Handler: mux,
  5. }
  6. }
  7. // NewServeMux creates a new http serve mux.
  8. func NewServeMux() *http.ServeMux {
  9. return &http.ServeMux{}
  10. }

Supported constructor signature:

  1. func([dep1, dep2, depN]) (result, [cleanup, error])

Now let’s teach a container to build these types.

  1. import (
  2. di "github.com/yoyofxteam/dependencyinjection"
  3. )
  4. container := di.New(
  5. // provide http server
  6. di.Provide(NewServer),
  7. // provide http serve mux
  8. di.Provide(NewServeMux)
  9. )

The function di.New() parse our constructors, compile dependency graph and return *di.Container type for interaction. Container panics if it could not compile.

I think that panic at the initialization of the application and not in runtime is usual.

Extraction

We can extract the built server from the container. For this, define the variable of extracted type and pass variable pointer to Extract function.

If extracted type not found or the process of building instance cause error, Extract return error.

If no error occurred, we can use the variable as if we had built it yourself.

  1. // declare type variable
  2. var server *http.Server
  3. // extracting
  4. err := container.Extract(&server)
  5. if err != nil {
  6. // check extraction error
  7. }
  8. server.ListenAndServe()

Note that by default, the container creates instances as a singleton. But you can change this behaviour. See Prototypes.

Invocation

As an alternative to extraction we can use Invoke() function. It resolves function dependencies and call the function. Invoke function may return optional error.

  1. // StartServer starts the server.
  2. func StartServer(server *http.Server) error {
  3. return server.ListenAndServe()
  4. }
  5. container.Invoke(StartServer)

Lazy-loading

Result dependencies will be lazy-loaded. If no one requires a type from the container it will not be constructed.

Interfaces

Inject make possible to provide implementation as an interface.

  1. // NewServer creates a http server with provided mux as handler.
  2. func NewServer(handler http.Handler) *http.Server {
  3. return &http.Server{
  4. Handler: handler,
  5. }
  6. }

For a container to know that as an implementation of http.Handler is necessary to use, we use the option di.As(). The arguments of this option must be a pointer(s) to an interface like new(Endpoint).

This syntax may seem strange, but I have not found a better way to specify the interface.

Updated container initialization code:

  1. container := inject.New(
  2. // provide http server
  3. inject.Provide(NewServer),
  4. // provide http serve mux as http.Handler interface
  5. inject.Provide(NewServeMux, inject.As(new(http.Handler)))
  6. )

Now container uses provide *http.ServeMux as http.Handler in server constructor. Using interfaces contributes to writing more testable code.

Groups

Container automatically groups all implementations of interface to []<interface> group. For example, provide with inject.As(new(http.Handler) automatically creates a group []http.Handler.

Let’s add some http controllers using this feature. Controllers have typical behavior. It is registering routes. At first, will create an interface for it.

  1. // Controller is an interface that can register its routes.
  2. type Controller interface {
  3. RegisterRoutes(mux *http.ServeMux)
  4. }

Now we will write controllers and implement Controller interface.

OrderController
  1. // OrderController is a http controller for orders.
  2. type OrderController struct {}
  3. // NewOrderController creates a auth http controller.
  4. func NewOrderController() *OrderController {
  5. return &OrderController{}
  6. }
  7. // RegisterRoutes is a Controller interface implementation.
  8. func (a *OrderController) RegisterRoutes(mux *http.ServeMux) {
  9. mux.HandleFunc("/orders", a.RetrieveOrders)
  10. }
  11. // Retrieve loads orders and writes it to the writer.
  12. func (a *OrderController) RetrieveOrders(writer http.ResponseWriter, request *http.Request) {
  13. // implementation
  14. }
UserController
  1. // UserController is a http endpoint for a user.
  2. type UserController struct {}
  3. // NewUserController creates a user http endpoint.
  4. func NewUserController() *UserController {
  5. return &UserController{}
  6. }
  7. // RegisterRoutes is a Controller interface implementation.
  8. func (e *UserController) RegisterRoutes(mux *http.ServeMux) {
  9. mux.HandleFunc("/users", e.RetrieveUsers)
  10. }
  11. // Retrieve loads users and writes it using the writer.
  12. func (e *UserController) RetrieveUsers(writer http.ResponseWriter, request *http.Request) {
  13. // implementation
  14. }

Just like in the example with interfaces, we will use inject.As() provide option.

  1. container := inject.New(
  2. di.Provide(NewServer), // provide http server
  3. di.Provide(NewServeMux), // provide http serve mux
  4. // endpoints
  5. di.Provide(NewOrderController, di.As(new(Controller))), // provide order controller
  6. di.Provide(NewUserController, di.As(new(Controller))), // provide user controller
  7. )

Now, we can use []Controller group in our mux. See updated code:

  1. // NewServeMux creates a new http serve mux.
  2. func NewServeMux(controllers []Controller) *http.ServeMux {
  3. mux := &http.ServeMux{}
  4. for _, controller := range controllers {
  5. controller.RegisterRoutes(mux)
  6. }
  7. return mux
  8. }

Advanced features

Named definitions

In some cases you have more than one instance of one type. For example two instances of database: master - for writing, slave - for reading.

First way is a wrapping types:

  1. // MasterDatabase provide write database access.
  2. type MasterDatabase struct {
  3. *Database
  4. }
  5. // SlaveDatabase provide read database access.
  6. type SlaveDatabase struct {
  7. *Database
  8. }

Second way is a using named definitions with di.WithName() provide option:

  1. // provide master database
  2. di.Provide(NewMasterDatabase, di.WithName("master"))
  3. // provide slave database
  4. di.Provide(NewSlaveDatabase, di.WithName("slave"))

If you need to extract it from container use di.Name() extract option.

  1. var db *Database
  2. container.Extract(&db, di.Name("master"))

If you need to provide named definition in other constructor use di.Parameter with embedding.

  1. // ServiceParameters
  2. type ServiceParameters struct {
  3. di.Parameter
  4. // use `di` tag for the container to know that field need to be injected.
  5. MasterDatabase *Database `di:"master"`
  6. SlaveDatabase *Database `di:"slave"`
  7. }
  8. // NewService creates new service with provided parameters.
  9. func NewService(parameters ServiceParameters) *Service {
  10. return &Service{
  11. MasterDatabase: parameters.MasterDatabase,
  12. SlaveDatabase: parameters.SlaveDatabase,
  13. }
  14. }

Optional parameters

Also di.Parameter provide ability to skip dependency if it not exists in container.

  1. // ServiceParameter
  2. type ServiceParameter struct {
  3. di.Parameter
  4. Logger *Logger `di:"optional"`
  5. }

Constructors that declare dependencies as optional must handle the case of those dependencies being absent.

You can use naming and optional together.

  1. // ServiceParameter
  2. type ServiceParameter struct {
  3. di.Parameter
  4. StdOutLogger *Logger `di:"stdout"`
  5. FileLogger *Logger `di:"file,optional"`
  6. }

Parameter Bag

If you need to specify some parameters on definition level you can use inject.ParameterBag provide option. This is a map[string]interface{} that transforms to di.ParameterBag type.

  1. // Provide server with parameter bag
  2. di.Provide(NewServer, di.ParameterBag{
  3. "addr": ":8080",
  4. })
  5. // NewServer create a server with provided parameter bag. Note: use di.ParameterBag type.
  6. // Not inject.ParameterBag.
  7. func NewServer(pb di.ParameterBag) *http.Server {
  8. return &http.Server{
  9. Addr: pb.RequireString("addr"),
  10. }
  11. }

Prototypes

If you want to create a new instance on each extraction use di.Prototype() provide option.

  1. di.Provide(NewRequestContext, di.Prototype())

todo: real use case

Cleanup

If a provider creates a value that needs to be cleaned up, then it can return a closure to clean up the resource.

  1. func NewFile(log Logger, path Path) (*os.File, func(), error) {
  2. f, err := os.Open(string(path))
  3. if err != nil {
  4. return nil, nil, err
  5. }
  6. cleanup := func() {
  7. if err := f.Close(); err != nil {
  8. log.Log(err)
  9. }
  10. }
  11. return f, cleanup, nil
  12. }

After container.Cleanup() call, it iterate over instances and call cleanup function if it exists.

  1. container := di.New(
  2. // ...
  3. di.Provide(NewFile),
  4. )
  5. // do something
  6. container.Cleanup() // file was closed

Cleanup now work incorrectly with prototype providers.

Visualization

Dependency graph may be presented via (Graphviz依赖注入 - dependencyinjection - 图1 (opens new window)). For it, load string representation:

  1. var graph *di.di.Graph
  2. if err = container.Extract(&graph); err != nil {
  3. // handle err
  4. }
  5. dotGraph := graph.String() // use string representation

And paste it to graphviz online tool:

依赖注入 - dependencyinjection - 图2