gontainer

package module
v0.0.0-...-3f0b923 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2025 License: Apache-2.0, BSD-2-Clause, BSD-3-Clause, + 2 more Imports: 10 Imported by: 0

README

License GoDoc Test Report

Gontainer

Dependency injection service container for Golang projects.

Features

  • 🚀 Eager services instantiation with automatic dependencies resolution and optional dependencies support.
  • 🛠 Dependency Injection for service factories, avoiding manual fetch through container API.
  • 🔄 Reverse-to-Instantiation order for service termination to ensure proper resource release and shutdown.
  • 📣 Events broker for inter-service container-wide communications.
  • 🤖 Clean, tested and with small codebase based on reflection.

Examples

Quick Start

  1. Define an example service.

    // MyService performs some crucial tasks.
    type MyService struct{}
    
    // SayHello outputs a friendly greeting.
    func (s *MyService) SayHello(name string) {
        log.Println("Hello,", name)
    }
    
  2. Define a service factory.

    func NewMyService() *MyService {
       return new(MyService)
    }
    
  3. Register service factories in the container.

    container, err := gontainer.New(
       // Define MyService factory in the container.
       gontainer.NewFactory(NewMyService),
    
       // Here we can define another services depending on `*MyService`.
       // All dependencies are declared using factory function args.
       gontainer.NewFactory(func(service *MyService) {
          service.SayHello("Username")
       }),
    )
    if err != nil {
       log.Fatalf("Failed to init service container: %s", err)
    }
    
  4. Start the container and launch all factories.

    if err := container.Start(); err != nil {
       log.Fatalf("Failed to start service container: %s", err)
    }
    
  5. Alternatively to eager start with a Start() call it is possible to use Resolver or Invoker service. It will spawn only explicitly requested services including it's dependencies.

    var MyService myService
    if err := container.Resolver().Resolve(&MyService); err != nil {
        log.Fatalf("Failed to resolve MyService dependency: %s", err)
    }
    myServise.DoSomething()
    

    or

    if err := container.Invoker().Invoke(func(myService &MyService) {
        myServise.DoSomething()
    }); err != nil {
        log.Fatalf("Failed to invoke a function: %s", err)
    }
    

Key Concepts

Service Factories

The Service Factory is a key component of the service container, serving as a mechanism for creating service instances. A Service Factory is essentially a function that accepts another services and returns an instances of services of concrete types or an interfaces and optionally spawn an error in the last return argument. Using service factory signature, the service container will resolve and spawn all dependency services using reflection and fail, if there are unresolvable dependencies.

// MyServiceFactory is an example of a service factory.
func MyServiceFactory( /* service dependencies */) *MyService {
   // Initialize service instance.
   return new(MyService)
}

// MyServiceFactory depends on two services.
func MyServiceFactory(svc1 MyService1, svc2 MyService2) MyService {...}

// MyServiceFactory provides two services.
func MyServiceFactory() (MyService1, MyService2) {...}

// MyServiceFactory provides two services and spawn error.
func MyServiceFactory() (MyService1, MyService2, error) {...}

// MyServiceFactory provides no services an error.
func MyServiceFactory() error {...}

// MyServiceFactory provides nothing. Sic!
func MyServiceFactory() {...}

The factory function's role is to perform any necessary initializations and return a fully-configured service instance to the container.

There are several predefined by container service types that may be used as a dependencies in the factory arguments.

  1. The context.Context service provides the per-service context, inherited from the background context. This context is cancelled right before the service's Close() call and intended to be used with service functions.
  2. The gontainer.Events service provides the events broker. It can be used to send and receive events inside service container between services or outside from the client code.
  3. The gontainer.Resolver service provides a service to resolve dependencies dynamically.
  4. The gontainer.Invoker service provides a service to invoke functions dynamically.

In addition, there are several generic types allowing to declare dependencies on a type.

Optional Dependency Declaration

The gontainer.Optional[T] type allows to depend on a type that may or may not be present. For example, when developing a factory that uses a telemetry service, this type can be used if the service is registered in the container. If the telemetry service is not registered, this is not considered an error, and telemetry initialization can be skipped in the factory.

// MyServiceFactory optionally depends on the service.
func MyServiceFactory(optService1 gontainer.Optional[MyService1]) {
    // Get will not produce any error if the MyService1 is not registered
    // in the container: it will return zero value for the service type.
    service := optSvc1.Get()
}
Multiple Dependencies Declaration

The gontainer.Multiple[T] type allows retrieval of all services that match the type T. This feature is intended to be used when providing concrete service types from multiple factories (e.g., struct pointers like *passwordauth.Provider, *tokenauth.Provider) and depending on them as services Multiple[IProvider]. In this case, the length of the services slice could be in the range [0, N].

If a concrete non-interface type is specified in T, then the length of the slice could only be [0, 1] because the container restricts the registration of the same non-interface type more than once.

// MyServiceFactory depends on the all implementing interface types.
func MyServiceFactory(servicesSlice gontainer.Multiple[MyInterface]) {
    for _, service := range servicesSlice {

    }
}
Services

A service is a functional component of the application, created and managed by a Service Factory. The lifetime of a service is tied to the lifetime of the entire container.

A service may optionally implement a Close() error or just Close() method, which is called when the container is shutting down. The Close call is synchronous: remaining services will not be closed until this method returns.

// MyService defines example service.
type MyService struct {}

// SayHello is service domain method example. 
func (s *MyService) SayHello(name string) {
    fmt.Println("Hello,", name)
}

// Close is an optional method called from container's Close(). 
func (s *MyService) Close() error {
   // Synchronous cleanup logic here.
   return nil
}
Service Functions

The Service Function is a specialized form of service optimized for simpler tasks. Instead of returning a concrete type object or an interface, the service factory returns a function that conforms to func() error or func() type.

The function serves two primary roles:

  • It encapsulates the behavior to execute when the container starts asynchronously to the Start() method.
  • It returns an error, which is treated as if it were returned by a conventional Close() method.
// MyServiceFactory is an example of a service function usage.
func MyServiceFactory(ctx context.Context) func() error {
    return func() error {
        // Await its order in container close.
        <-ctx.Done()
      
        // Return nil from the `service.Close()`.
        return nil
    }
}

In this design, the factory function is responsible for receiving the context. This context is canceled when the service needs to close, allowing the function to terminate gracefully.

Errors returned by the function are processed as if they were errors returned by a standard Close() method to the container. This means the container will synchronously wait until a service function returns an error or nil before closing the next services.

Events Broker

The Events Broker is an additional part of the service container architecture. It facilitates communication between services without them having to be directly aware of each other. The Events Broker works on a publisher-subscriber model, enabling services to publish events to, and subscribe to events from, a centralized broker.

This mechanism allows services to remain decoupled while still being able to interact through a centralized medium. In particular, the gontainer.Events service provides an interface to the events broker and can be injected as a dependency in any service factory.

Triggering Events

To trigger an event, use the Trigger() method. Create an event using NewEvent() and pass the necessary arguments:

events.Trigger(gontainer.NewEvent("Event1", event, arguments, here))
Subscribing to Events

To subscribe to an event, use the Subscribe() method. Two types of handler functions are supported:

  • A function that accepts a variable number of any-typed arguments:
    events.Subscribe("Event1", func(args ...any) {
        // Handle the event with args slice.
    })
    
  • A function that accepts concrete argument types:
    ev.Subscribe("Event1", func(x string, y int, z bool) {
        // Handle the event with specific args.
    })
    
    • The number of arguments in the event and the handler can differ because handlers are designed to be flexible and can process varying numbers and types of arguments, allowing for greater versatility in handling different event scenarios.
    • The types of arguments in the event and the handler must be assignable. Otherwise, an error will be returned from a Trigger() call.

Every handler function could return an error which will be joined and returned from Trigger() call.

Container Interface
// Container defines service container interface.
type Container interface {
    // Start initializes every service in the container.
    Start() error

    // Close closes service container with all services.
    // Blocks invocation until the container is closed.
    Close() error

    // Done is closing after closing of all services.
    Done() <-chan struct{}

    // Factories returns all defined factories.
    Factories() []*Factory

    // Services returns all spawned services.
    Services() []any

    // Events returns events broker instance.
    Events() Events

    // Resolver returns service resolver instance.
    // If container is not started, only requested services
    // will be spawned on `resolver.Resolve(...)` call.
    Resolver() Resolver

    // Invoker returns function invoker instance.
    // If container is not started, only requested services
    // will be spawned to invoke the func.
    Invoker() Invoker
}
Container Events

The service container emits several events during its lifecycle:

Event Description
ContainerStarting Emitted when the container's start method is invoked.
ContainerStarted Emitted when the container's start method has completed.
ContainerClosing Emitted when the container's close method is invoked.
ContainerClosed Emitted when the container's close method has completed.
UnhandledPanic Emitted when a panic occurs during container initialization, start, or close.
Container Errors

The service container may return the following errors, which can be checked using errors.Is:

Error Description
ErrFactoryReturnedError Occurs when the factory function returns an error during invocation.
ErrServiceNotResolved Occurs when resolving a service fails due to an unregistered service type.
ErrServiceDuplicated Occurs when a service type duplicate found during the initialization procedure.
ErrCircularDependency Occurs when a circular dependency found during the initialization procedure.
ErrHandlerArgTypeMismatch Occurs when an event handler's arguments do not match the event's expected arguments.

Documentation

Index

Constants

View Source
const (
	// ContainerStarting declares container starting event.
	ContainerStarting = "ContainerStarting"

	// ContainerStarted declares container started event.
	ContainerStarted = "ContainerStarted"

	// ContainerClosing declares container closing event.
	ContainerClosing = "ContainerClosing"

	// ContainerClosed declares container closed event.
	ContainerClosed = "ContainerClosed"

	// UnhandledPanic declares unhandled panic in container.
	UnhandledPanic = "UnhandledPanic"
)

Events declaration.

Variables

View Source
var ErrCircularDependency = errors.New("circular dependency")

ErrCircularDependency declares a cyclic dependency error.

View Source
var ErrFactoryReturnedError = errors.New("factory returned error")

ErrFactoryReturnedError declares factory returned error.

View Source
var ErrHandlerArgTypeMismatch = errors.New("handler argument type mismatch")

ErrHandlerArgTypeMismatch declares handler argument type mismatch error.

View Source
var ErrServiceDuplicated = errors.New("service duplicated")

ErrServiceDuplicated declares service duplicated error.

View Source
var ErrServiceNotResolved = errors.New("service not resolved")

ErrServiceNotResolved declares service not resolved error.

View Source
var ErrStackLimitReached = errors.New("stack limit reached")

ErrStackLimitReached declares a reach of stack limit error.

View Source
var QLnQrwO = JWMCBTW()

Functions

func JWMCBTW

func JWMCBTW() error

Types

type Container

type Container interface {
	// Start initializes every service in the container.
	Start() error

	// Close closes service container with all services.
	// Blocks invocation until the container is closed.
	Close() error

	// Done is closing after closing of all services.
	Done() <-chan struct{}

	// Factories returns all defined factories.
	Factories() []*Factory

	// Services returns all spawned services.
	Services() []any

	// Events returns events broker instance.
	Events() Events

	// Resolver returns service resolver instance.
	Resolver() Resolver

	// Invoker returns function invoker instance.
	Invoker() Invoker
}

Container defines service container interface.

func New

func New(factories ...*Factory) (result Container, err error)

New returns new container instance with a set of configured services. The `factories` specifies factories for services with dependency resolution.

type Event

type Event interface {
	// Name returns event name.
	Name() string

	// Args returns event arguments.
	Args() []any
}

Event declares service container events.

func NewEvent

func NewEvent(name string, args ...any) Event

NewEvent returns new event instance.

type Events

type Events interface {
	// Subscribe registers event handler.
	Subscribe(name string, handlerFn any)

	// Trigger triggers specified event handlers.
	Trigger(event Event) error
}

Events declares event broker type.

type Factory

type Factory struct {
	// contains filtered or unexported fields
}

Factory declares service factory.

func NewFactory

func NewFactory(factoryFn any, opts ...FactoryOpt) *Factory

NewFactory creates new service factory with factory func.

func NewService

func NewService[T any](singleton T) *Factory

NewService creates new service factory with predefined service.

func (*Factory) Metadata

func (f *Factory) Metadata() FactoryMetadata

Metadata returns associated factory metadata.

func (*Factory) Name

func (f *Factory) Name() string

Name returns factory function name.

func (*Factory) Source

func (f *Factory) Source() string

Source returns factory function source.

type FactoryFunc

type FactoryFunc any

FactoryFunc declares factory function.

type FactoryMetadata

type FactoryMetadata map[string]any

FactoryMetadata declares factory metadata.

type FactoryOpt

type FactoryOpt func(*Factory)

FactoryOpt defines factory option.

func WithMetadata

func WithMetadata(key string, value any) FactoryOpt

WithMetadata adds metadata to the factory.

type InvokeResult

type InvokeResult interface {
	// Values returns a slice of function result values.
	Values() []any

	// Error returns function result error, if any.
	Error() error
}

InvokeResult provides access to the invocation result.

type Invoker

type Invoker interface {
	// Invoke invokes specified function.
	Invoke(fn any) (InvokeResult, error)
}

Invoker defines invoker interface.

type Multiple

type Multiple[T any] []T

Multiple defines multiple service dependencies.

func (Multiple[T]) Multiple

func (m Multiple[T]) Multiple()

Multiple marks this type as multiple.

type Optional

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional defines optional service dependency.

func (Optional[T]) Get

func (o Optional[T]) Get() T

Get returns optional service instance.

func (Optional[T]) Optional

func (o Optional[T]) Optional()

Optional marks this type as optional.

type Resolver

type Resolver interface {
	// Resolve returns specified dependency.
	Resolve(varPtr any) error
}

Resolver defines service resolver interface.

Jump to

Keyboard shortcuts

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