ioc

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2023 License: MIT Imports: 4 Imported by: 5

README

ioc

Inversion of Control (IoC)

Feature

    1. Support service as singleton and transient
    1. Support resolve service by parent if not found in current
    1. Support inject to function or *struct with services that has registered

    Should add struct tag 'ioc-inject:"true"' to field if want to be injected, but field type ioc.Resolver is not necessary.

    1. Support override exists service

    Register to parent's container, and then register to current's to override parent's.

    1. Support inject to singleton instance automatically

    Inject to singleton instance and it's initialize method Initialize(XXX) or another one which the returns of method InitializeMethodName() string automatically.

    It will use zero value instead of panic if depended service not registerd.

Usage

package main

import (
    "github.com/berkaroad/ioc"
)

type Interface1 interface {
    GetC2Name() string
}

type Interface2 interface {
    GetName() string
}

type Class1 struct {
    Resolver ioc.Resolver
    C2       *Class2 `ioc-inject:"true"`
}

func (c *Class1) GetC2Name() string {
    return c.C2.Name
}

type Class2 struct {
    Name     string
    resolver ioc.Resolver
}

func (c *Class2) GetName() string {
    return c.Name
}

func (c *Class2) Initialize(resolver ioc.Resolver) string {
    c.resolver = resolver
    return c.Name
}

type Interface3 interface {
    GetName() string
}

type Class3 struct {
    Name     string
    resolver ioc.Resolver
}

func (c *Class3) GetName() string {
    return "Class3-" + c.Name
}

// specific custom initialize method name
func (c *Class3) InitializeMethodName() string {
    return "MyInitialize"
}

// custom initialize method
func (c *Class2) MyInitialize(resolver ioc.Resolver) string {
    c.resolver = resolver
    return c.Name
}

type Class4 struct {
    Name     string
}

func (c *Class4) GetName() string {
    return "Class3-" + c.Name
}

func main() {
    // register service to *struct
    ioc.AddSingleton[*Class2](&Class2{Name: "Jerry Bai"})
    ioc.AddTransient[*Class1](func() *Class1 {
        var svc Class1
        // inject to *struct
        ioc.Inject(&svc)
    }

    // register service to interface.
    ioc.AddSingleton[Interface2](&Class2{Name: "Jerry Bai"})
    ioc.AddTransient[Interface1](func() Interface1 {
        var svc Class1
        // inject to *struct
        ioc.Inject(&svc)
    }

    // get service from ioc
    c1 := ioc.GetService[*Class1]
    c2 := ioc.GetService[*Class2]
    i1 := ioc.GetService[Interface1]
    i2 := ioc.GetService[Interface2]

    // inject to function
    ioc.Inject(func(c1 *Class1, c2 *Class2, i1 Interface1, i2 Interface2, resolver ioc.Resolver) {
        println("c1.C2Name=", c1.C2.Name)
        println("c2.Name=", c2.Name)
        println("i1.GetC2Name=()", i1.GetC2Name())
        println("i2.GetName=()", i2.GetName())
    })

    // override exists service
    c := ioc.New()
    ioc.SetParent(c)
    ioc.AddSingletonToC[Interface3](c, &Class3{Name: "Jerry Bai"}) // add service to parent's container
    i3 := ioc.GetService[Interface3]() // *Class3, 'Interface3' only exists in parent's container
    ioc.AddSingleton[Interface3](&Class4{Name: "Jerry Bai"}) // add service to global's container
    i3 = ioc.GetService[Interface3]() // *Class4, 'Interface3' exists in both global and parent's container
}

Benchmark

go test -run=none -count=1 -benchtime=1000000x -benchmem -bench=. ./...

goos: linux
goarch: amd64
pkg: github.com/berkaroad/ioc
cpu: AMD Ryzen 7 5800H with Radeon Graphics         
BenchmarkGetSingletonService-4           1000000                26.16 ns/op            0 B/op          0 allocs/op
BenchmarkGetTransientService-4           1000000               370.9 ns/op            48 B/op          1 allocs/op
BenchmarkGetTransientServiceNative-4     1000000               131.9 ns/op            48 B/op          1 allocs/op
BenchmarkInjectToFunc-4                  1000000               659.5 ns/op           144 B/op          5 allocs/op
BenchmarkInjectToFuncNative-4            1000000                89.26 ns/op            0 B/op          0 allocs/op
BenchmarkInjectToStruct-4                1000000               311.7 ns/op             0 B/op          0 allocs/op
BenchmarkInjectToStructNative-4          1000000                87.64 ns/op            0 B/op          0 allocs/op
PASS
ok      github.com/berkaroad/ioc        1.686s

Documentation

Overview

Package ioc is Inversion of Control (IoC). Support singleton and transient.

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Index

Constants

View Source
const DefaultInitializeMethodName string = "Initialize"

Variables

This section is empty.

Functions

func AddSingleton added in v1.0.0

func AddSingleton[TService any](instance TService)

AddSingleton to add singleton instance.

It will panic if 'TService' or 'instance' is invalid.

// service
type Service1 interface {
    Method1()
}
// implementation of service
type ServiceImplementation1 struct {
    Field1 string

    resolver ioc.Resolver
}
func(si *ServiceImplementation1) Method1() {}
func(si *ServiceImplementation1) Initialize(resolver ioc.Resolver) {
    si.resolver = resolver
}

// interface as service
ioc.AddSingleton[Service1](&ServiceImplementation1{Field1: "abc"})
// or *struct as service
ioc.AddSingleton[*ServiceImplementation1](&ServiceImplementation1{Field1: "abc"})

func AddSingletonToC added in v1.1.0

func AddSingletonToC[TService any](container Container, instance TService)

AddSingletonToC to add singleton instance to container.

It will panic if 'TService' or 'instance' is invalid.

func AddTransient added in v1.0.0

func AddTransient[TService any](instanceFactory func() TService)

AddTransient to add transient service instance factory.

It will panic if 'TService' or 'instance' is invalid.

// service
type Service1 interface {
    Method1()
}
// implementation of service
type ServiceImplementation1 struct {
    Field1 string
}
func(si *ServiceImplementation1) Method1() {}

// interface as service
ioc.AddTransient[Service1](func() Service1 {
     return &ServiceImplementation1{Field1: "abc"}
})
// or *struct as service
ioc.AddTransient[*ServiceImplementation1](func() *ServiceImplementation1 {
     return &ServiceImplementation1{Field1: "abc"}
})

func AddTransientToC added in v1.1.0

func AddTransientToC[TService any](container Container, instanceFactory func() TService)

AddTransientToC to add transient service instance factory to container.

It will panic if 'TService' or 'instance' is invalid.

func GetService added in v1.0.0

func GetService[TService any]() TService

GetService to get service.

// service
type Service1 interface {
    Method1()
}
// implementation of service
type ServiceImplementation1 struct {
    Field1 string
}
func(si *ServiceImplementation1) Method1() {}

// interface as service
service1 := ioc.GetService[Service1]()
// or *struct as service
service2 := ioc.GetService[*ServiceImplementation1]()

func GetServiceFromC added in v1.1.0

func GetServiceFromC[TService any](container Container) TService

GetServiceFromC to get service from container.

func Inject added in v1.0.0

func Inject(target any)

Inject to func or *struct with service. Field with type 'ioc.Resolver', will always been injected.

It will panic if param type in func not registered in container.

// service
type Service1 interface {
    Method1()
}

// implementation of service
type ServiceImplementation1 struct {
    Field1 string
}
func(si *ServiceImplementation1) Method1() {}

// client
type Client struct {
    Field1 Service1 `ioc-inject:"true"`
    Field2 *ServiceImplementation1 `ioc-inject:"true"`
}
func(c *Client) Method1(p1 Service1, p2 *ServiceImplementation1) {
    c.Field1 = p1
    c.Field2 = p2
}

var c client
// inject to func
ioc.Inject(c.Method1)
// inject to *struct
ioc.Inject(&c)

func InjectFromC added in v1.1.0

func InjectFromC(container Container, target any)

InjectFromC to inject to func or *struct or their's reflect.Value with service from container. Field with type 'ioc.Resolver', will always been injected.

It will panic if param type in func not registered in container.

func SetParent added in v1.0.0

func SetParent(parent Resolver)

Set parent resolver, for resolving from parent if service not found in current.

Types

type Container

type Container interface {
	Resolver

	// AddSingleton to add singleton instance.
	//
	//  // service
	//  type Service1 interface {
	//      Method1()
	//  }
	//  // implementation of service
	//  type ServiceImplementation1 struct {
	//      Field1 string
	//  }
	//  func(si *ServiceImplementation1) Method1() {}
	//	func(si *ServiceImplementation1) Initialize(resolver ioc.Resolver) {
	//	    si.resolver = resolver
	//	}
	//
	//  var container ioc.Container
	//  // interface as service, register as singleton
	//  err := container.AddSingleton(reflect.TypeOf((*Service1)(nil)).Elem(), &ServiceImplementation1{Field1: "abc"})
	//  // or *struct as service, register as singleton
	//  err = container.AddSingleton(reflect.TypeOf((*ServiceImplementation1)(nil)), &ServiceImplementation1{Field1: "abc"})
	AddSingleton(serviceType reflect.Type, instance any) error

	// AddTransient to add transient by instance factory.
	//
	//  // service
	//  type Service1 interface {
	//      Method1()
	//  }
	//  // implementation of service
	//  type ServiceImplementation1 struct {
	//      Field1 string
	//  }
	//  func(si *ServiceImplementation1) Method1() {}
	//
	//  var container ioc.Container
	//  // interface as service, register as transient
	//  err = container.AddTransient(reflect.TypeOf((*Service1)(nil)).Elem(), func() any {
	//      return &ServiceImplementation1{Field1: "abc"}
	//  })
	//  // or *struct as service, register as transient
	//  err = container.AddTransient(reflect.TypeOf((*ServiceImplementation1)(nil)), func() any {
	//      return &ServiceImplementation1{Field1: "abc"}
	//  })
	AddTransient(serviceType reflect.Type, instanceFactory func() any) error
}

Inversion of Control container.

func New added in v1.1.0

func New() Container

New ioc container, and add singleton service 'ioc.Resolver' to it.

type CustomInitializer added in v1.2.0

type CustomInitializer interface {
	// InitializeMethodName indicate the initialize method name.
	// Won't be invoked if the method returns is not exists.
	InitializeMethodName() string
}

CustomInitializer that use customize initialize method instead of default method 'Initialize'

type Resolver added in v1.0.0

type Resolver interface {
	// Set parent resolver, for resolving from parent if service not found in current.
	SetParent(parent Resolver)

	// Resolve to get service.
	//
	//  // service
	//  type Service1 interface {
	//      Method1()
	//  }
	//  // implementation of service
	//  type ServiceImplementation1 struct {
	//      Field1 string
	//  }
	//  func(si *ServiceImplementation1) Method1() {}
	//
	//  var container ioc.Container
	//  // interface as service
	//  service1 := container.Resolve(reflect.TypeOf((*Service1)(nil)).Elem())
	//  // or *struct as service
	//  service2 := container.Resolve(reflect.TypeOf((*ServiceImplementation1)(nil)))
	Resolve(serviceType reflect.Type) reflect.Value
}

Resolver can resolve service.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL