RapidGo
No results found

Service Container

Dependency injection with the IoC service container.

RapidGo's service container manages dependency injection. Services are registered by name and resolved on demand.

Binding Services

import "github.com/RAiWorks/RapidGo/v2/core/container"

c := container.New()

// Transient — new instance every time
c.Bind("mailer", func(c *container.Container) interface{} {
    return mail.NewMailer()
})

// Singleton — created once, cached forever
c.Singleton("db", func(c *container.Container) interface{} {
    return database.Connect()
})

// Instance — register an existing object
c.Instance("config", myConfig)

Resolving Services

// Generic resolve
db := c.Make("db")

// Type-safe resolve with generics
db := container.MustMake[*gorm.DB](c, "db")

// Check if a service exists
if c.Has("redis") {
    redis := c.Make("redis")
}

How It Works

  1. Bind registers a factory function — called every time you Make()
  2. Singleton registers a factory that runs once — result is cached
  3. Instance stores an already-created object directly
  4. Make checks instances first, then calls the factory