Categorygithub.com/go-zoox/ioc
modulepackage
1.0.2
Repository: https://github.com/go-zoox/ioc.git
Documentation: pkg.go.dev

# README

Container - Simple Dependency Injection Container

PkgGoDev Build Status Go Report Card Coverage Status GitHub issues Release

Installation

To install the package, run:

go get github.com/go-zoox/container

Getting Started

import (
  "testing"
  "github.com/go-zoox/container"
)

func main(t *testing.T) {
	container.Register("config", Config.New())
	container.Register("logger",	Logger.New())
	// container.Register("database", Database.New())
	container.Register("service.user", UserService.New())
	// container.Register("service.post", PostService.New())
}
// config/config.go
package config

import (
	cfg "github.com/go-zoox/config"
)

type Config struct {
	Database struct {
		Host string
		Port int
	}
	Logger struct {
		Level string
	}
}

func New() *Config {
	var c Config
	if err := cfg.Load(&c); err != nil {
		panic(err)
	}
	return &c
}
// logger/logger.go
package logger

import (
	log "github.com/go-zoox/logger"
)

func New() *log.Logger {
	return log.New()
}
// service/user.go
package service

type UserService struct {
	Config *Config
	Logger *log.Logger
}


func New() *UserService {
	return &UserService{
		Config: container.MustGet("config").(*Config),
		Logger: container.MustGet("logger").(*log.Logger),
	}
}

func (u *UserService) GetUser(id int) (*User, error) {
	u.Logger.Info("GetUser")

	return &User{
		ID: id,
		Name: "John Doe",
	}, nil
}

Inspired by

  • vardius/gocontainer - Simple Dependency Injection Container
  • golobby/container - A lightweight yet powerful IoC dependency injection container for the Go programming language
  • goava/di - 🛠 A full-featured dependency injection container for go programming language
  • goioc/di - Simple and yet powerful Dependency Injection for Go

License

GoZoox is released under the MIT License.

# Functions

Get gets a service by id.
Has checks if a service exists within the container.
Invoke gets a service safely typed by passing it to a closure will panic if callback is not a function.
MustGet calls Get underneath will panic if serviceect not found within container.
MustInvoke calls MustGet underneath will panic if service not found within container.
New creates a new DI Container.
Register service by id.

# Variables

Version is the current version of the package.

# Interfaces

Container is DI Container.