Skip to content

Service Container

David Ciulla edited this page Nov 7, 2026 · 1 revision

Service Container

Introduction

The Laravex service container is a lightweight IoC (Inversion of Control) container modelled directly on Laravel's Illuminate\Container\Container. It is implemented as a GenServer (Laravex.Container) that the OTP supervisor starts before the application boots, making it available to every service provider and throughout the request lifecycle.

The container supports three binding types — bind (transient), singleton, and instance — plus a call helper for dependency injection into arbitrary functions and MFAs.


How the Container Works

Laravex.Container (GenServer)
│
├── bind/2       ─ factory function, called fresh on every make/2
├── singleton/2  ─ factory function, called once; result cached
├── instance/2   ─ pre-built value; returned as-is
│
└── make/2       ─ resolve any registered abstract; falls back to abstract.new()

Binding

Transient Binding (bind/2)

A new instance is produced each time make/2 is called:

Laravex.Container.bind(MyApp.Mailer, fn _params ->
  MyApp.Mailer.new(host: "smtp.example.com")
end)

Singleton Binding (singleton/2)

The factory is called once; subsequent make/2 calls return the same value:

Laravex.Container.singleton(MyApp.PaymentGateway, fn _params ->
  MyApp.PaymentGateway.connect(
    key: Laravex.Config.Repository.get("services.stripe.key")
  )
end)

Tip: Service providers call singleton/2 in their register/0 callback so the binding is in place before boot/0 runs. See Service-Providers.

Instance Binding (instance/2)

Register a pre-built value directly:

Laravex.Container.instance(MyApp.Config, %{env: "production", debug: false})

Resolving (Making)

Use make/2 to resolve a binding:

mailer = Laravex.Container.make(MyApp.Mailer)

# Pass optional params to the factory function
gateway = Laravex.Container.make(MyApp.PaymentGateway, [currency: "USD"])

If no binding is registered for abstract, the container tries abstract.new(). If that is not exported either, the atom itself is returned.


Calling with Dependency Injection

call/2 invokes a function or MFA, forwarding optional parameters:

# Anonymous function
Laravex.Container.call(fn params -> IO.inspect(params) end, [a: 1])

# Module + function atom
Laravex.Container.call({MyApp.Handlers.CreateUser, :handle}, [attrs: %{}])

# Module + function + pre-bound args (extra params appended)
Laravex.Container.call({MyApp.Jobs.Send, :perform, [job]}, [retry: true])

Checking Bindings

Laravex.Container.bound?(MyApp.Mailer)
#=> true | false

Flushing the Container

Clears all bindings and cached singletons. Useful in tests:

Laravex.Container.flush()

Full API Reference

Function Description
bind(abstract, concrete) Register a transient factory (concrete is fn params -> … end)
singleton(abstract, concrete) Register a singleton factory (resolved once)
instance(abstract, value) Register a pre-built value
make(abstract, params \\ []) Resolve a binding
call(fun_or_mfa, params \\ []) Invoke a function or MFA with optional params
bound?(abstract) Check whether abstract has a registered binding
flush() Remove all bindings and cached singletons

All functions are synchronous GenServer.call/2 operations and are safe to call from any process.


Container in Service Providers

The standard pattern is to register bindings in register/0 and use them in boot/0:

defmodule App.Providers.AppServiceProvider do
  def register do
    Laravex.Container.singleton(App.Services.StripeClient, fn _params ->
      App.Services.StripeClient.new(
        secret: Laravex.Config.Repository.get("services.stripe.secret")
      )
    end)
  end

  def boot do
    # bindings are now available
    _client = Laravex.Container.make(App.Services.StripeClient)
    :ok
  end
end

See Service-Providers for how providers are discovered and booted.

Clone this wiki locally