Home

Awesome

πŸͺ£ gocontainer

Build Status Go Report Card codecov license

<img align="right" height="180px" src="https://github.com/vardius/gorouter/blob/master/website/src/static/img/logo.png?raw=true" alt="logo" />

gocontainer - Dependency Injection Container

πŸ“– ABOUT

Contributors:

Want to contribute ? Feel free to send pull requests!

Have problems, bugs, feature ideas? We are using the github issue tracker to manage them.

πŸ“š Documentation

For examples visit godoc#pkg-examples

For GoDoc reference, visit pkg.go.dev

MustInvokeMany

🚏 HOW TO USE

First file main.go simply gets the repository from the container and prints it we use MustInvoke method to simply present the way where we keep type safety

package main

import (
    "github.com/vardius/gocontainer/example/repository"
    "github.com/vardius/gocontainer"
)

func main() {
    gocontainer.MustInvoke("repository.mysql", func(r Repository) {
        fmt.Println(r)
    })
}

Our database implementation uses init() function to register db service

package database

import (
    "fmt"
    "database/sql"

    "github.com/vardius/gocontainer"
)

func NewDatabase() *sql.DB {
    db, _ := sql.Open("mysql", "dsn")

    return db
}

func init() {
    db := gocontainer.MustGet("db")

    gocontainer.Register("db", NewDatabase())
}

Our repository accesses earlier on registered db service and following the same patter uses init() function to register repository service within container

package repository

import (
    "fmt"
    "database/sql"

    "github.com/vardius/gocontainer"
    _ "github.com/vardius/gocontainer/example/database"
)

type Repository interface {}

func NewRepository(db *sql.DB) Repository {
    return &mysqlRepository{db}
}

type mysqlRepository struct {
    db *sql.DB
}

func init() {
    db := gocontainer.MustGet("db")

    gocontainer.Register("repository.mysql", NewRepository(db.(*sql.DB)))
}

You can disable global container instance by setting gocontainer.GlobalContainer to nil. This package allows you to create many containers.

package main

import (
    "github.com/vardius/gocontainer/example/repository"
    "github.com/vardius/gocontainer"
)

func main() {
    // disable global container instance
    gocontainer.GlobalContainer = nil

    mycontainer := gocontainer.New()
    mycontainer.Register("test", 1)
}

Please check GoDoc for more methods and examples.

πŸ“œ License

This package is released under the MIT license. See the complete license in the package