Skip to content

nikonm/go-container

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

codecov Build Status

DI Container

  • Container uses reflect on initialization
  • Uses auto-substitution in the service initialization function, return error if circle dependency loop found
  • Supports stopping services, can be used for graceful exit. Use the Stopper interface for it
  • There is a utility function "GetPkgPath" to get the package name + structure

Example

type Service1 struct {
   Service2 *Service2 
}
func NewService1(s *Service2) (*Service1, error) {
   return &Service1{Service2: s}, nil
}

type Service2 struct {}
func (s2 *Service2) Stop() error {
   return nil
}

func NewService2() (*Service2, error) {
   return &Service2{}, nil
}

func main() {
   container, err := New(&Options{
   	BasePkg:  "go_container", // you can use it for shorten name resolving
   	Services: []interface{}{
   		NewService2,
   		NewService1,
   	},
   })
   service2 := container.GetService("Service2").(*Service2) // Returning Service2 instance

   err := container.StopAll() // Call all Stop functions in each service(Graceful exit) 
}

Example with NamedOptions

type Service1 struct {
   Service2 *Service2 
}
func NewService1(s *Service2) (*Service1, error) {
   return &Service1{Service2: s}, nil
}

type Service2 struct {}
func (s2 *Service2) Stop() error {
   return nil
}

func NewService2() (*Service2, error) {
   return &Service2{}, nil
}

func main() {
   const serv2  = "custom_name2"
   container, err := NewNamed(&NamedOptions{
                     		Services: map[string]interface{}{
                     			serv2: NewService2,
                     		},
                     	})
   service2 := container.GetService(serv2).(*Service2) // Returning Service2 instance

   err := container.StopAll() // Call all Stop functions in each service(Graceful exit) 
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages