roids

package module
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2025 License: AGPL-3.0 Imports: 15 Imported by: 0

README


Roids: Dependency Injection

FeaturesGetting StartedUsageBuildingEnhancements


Roids Logo

Roids is a simple dependency injection container that you can use to share and pass services into your application.


Roids Main Build

Features

  • Simple setup
    • global container instance
    • automatic and manual injecting
    • out of order configuration
    • error handling only on setup
  • Constructor-like dependency injection
  • 2 dependency lifetimes:
    • Static: Created once and shared. Lives for life of container.
    • Transient: Created everytime it is injected. Lives for life of the dependency using it, or life of the last pointer referencing it.
  • Http-Framework agnostic

Get Roids

go get github.com/ShounakA/roids

Usage

Configuration File

You can add your own configuration file. The name of the file can be anything, but must follow a certain interface (shape). Only JSON and Yaml files are currently supported.

{
	// the "roids" field is currently required. 
    "roids": {
        "version": "0.4.0"
    },
    "app": {
		// this should match the shape of the struct you want to add.
        "message": "Test from JSON",
        "somenumber": 420,
        "somearray": [
            "this is a test",
            "this is a another test",
            "here is another"
        ],
        "complextype": {
            "somenumber2": 12.4,
            "otherarray": [
                123, 456, 987
            ]
        }
    }
}
# roids field is required.
roids:
  version: 0.4.0
# this should match the shape of the struct you want to add.
app:
  message: "Test from YAML"
  somenumber: 69
  somearray:
  - "this is a test"
  - "this is a another test"
  - "here is another"
  complextype:
    somenumber2: 12.4
    otherarray:
    - 123
    - 456
    - 987


type TestConfig struct {
	Message string `json:"message"`
	SomeNumber int `json:"somenumber"`
	SomeArray []string `json:"somearray"`
	ComplexType struct {
		SomeNumber2 float64 `json:"somenumber2"`
		OtherArray []float64 `json:"otherarray"`
	} `json:"complextype"`
}

type interface HelloWorld {
	SayHello() string
}

type struct Hw {
	message string
}

func (hw *Hw) SayHello() {
	println("hello,", hw.message)
	return hw.message
}

func main() {

    // Instantiate the one and only roids container
	_ = roids.GetRoids()
	
	// [Optional] add a configuration file. You can inject this config anywhere in your app.
	err := roids.AddConfigurationBuilder[TestConfig]("./roids.settings.json", core.JsonConfig)
	if err != nil {
		e.Logger.Fatal("Could not read configuration file.")
	}

    // Add your servicess
	roids.AddStaticService(new(HelloWorld), func(configAdapter config.IConfiguration[TestConfig]) {
		config := configAdapter.Config()
		return &Hw {
			message: config.Message
		}
	})
	
	// Build your needle, to instantiate your services
	roids.Build()


	// Do stuff
	e.GET("/", func(c echo.Context) error {
		// Inject your instantiated services with configured implementations anywhere in your app
		helloService := roids.Inject[HelloWorld]()

		return c.String(http.StatusOK, helloService.SayHello())
	})
	e.Logger.Fatal(e.Start(":1323"))
s
}

Building roids

Prerequisites
  • Golang 1.21.1 +
Build module
	go build
Test module
	go test
Run example application
	go run testapp/main.go

Enhancements

  • Internal logging
  • Startup/Cleanup actions for services

Documentation

Overview

Package containing custom dependency container for dependency injection. There is only ever one container and it can be used globally to access all the dependencies.

Package containing custom dependency container for dependency injection. There is only ever one container and it can be used globally to access all the dependencies.

Package containing custom dependency container for dependency injection. There is only ever one container and it can be used globally to access all the dependencies.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddConfigurationBuilder added in v0.4.0

func AddConfigurationBuilder[T any](filePath string, cfgType core.ConfigType) error

Add a custom configuration file. Default roids.settings.json file.

func AddCustomConfiguration added in v0.4.0

func AddCustomConfiguration[T any](configurationRead func() ([]byte, error), cfgType core.ConfigType) error

Add Custom Configuration configuraitonRead expects a slice of bytes encoded as json or yaml depending on the config type.

func AddStaticService added in v0.2.0

func AddStaticService[T interface{}](spec T, impl any) error

Adds a static service to the container. A static service is only created once and lives for the life of the application. Uses the specification (interface or struct) to inject an implementation into the IoC container

func AddTransientService added in v0.2.0

func AddTransientService[T interface{}](spec T, impl any) error

Adds a transient service to the container. A transient service is newly instantiated for each use.

func Build

func Build() error

Builds all static services in container.

func GetRoids

func GetRoids() *roidsContainer

Thread-safe function to get the global instance of the dependency container.

func Inject

func Inject[T interface{}]() T

Gets an implementation of a service based on an specification from the container.

func UNSAFE_Clear

func UNSAFE_Clear()

Clears the container of all services SUPER UNSAFE. Only used during testing. Dont use while running an application.

Types

type Service

type Service struct {
	// Injector is a function that returns a pointer to a concrete implementation
	Injector any
	// ID representing and identifying the service
	Id string
	// The service specification or interface type
	SpecType reflect.Type
	// contains filtered or unexported fields
}

Struct representing an injectable service. (aka Provider, Assembler, Service, or Injector)

func (*Service) ID added in v0.2.0

func (s *Service) ID() string

ID function for *Service type.

func (*Service) String added in v0.2.0

func (s *Service) String() string

String function for *Service type.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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