abstract class Radbas::Container

Overview

A small dependency injection container, wired at compile time.

Extend Radbas::Container and register services in the class body:

class MyContainer < Radbas::Container
  # resolve every class inside these namespaces automatically
  autowire(MyApp, CustomNamespace)

  # register all concrete subclasses of an abstract class
  register_subclasses(MyApp::Handler, public: true)

  # register a single service, constructor dependencies are injected
  register(DependencyService)

  # set constructor arguments explicitly, `get` resolves other entries
  register(MyService, params: {dep: get(DependencyService), name: "my"})

  # or build the service yourself with a call or proc
  register(OtherService, factory: -> { OtherService.new(get(DependencyService)) })

  # public entries can be fetched from outside the container
  register(MyApplication, public: true)
end

MyContainer.new.get(MyApplication).run

Registration macros:

Services are created lazily on the first #get and then cached, so every container instance holds exactly one instance per service. Configuration errors are reported at compile time.

Defined in:

radbas-container.cr

Constant Summary

VERSION = "1.0.0"

Instance Method Summary

Instance Method Detail

def get(id : T.class) forall T #

Returns the container itself when id is the container class or one of its ancestors.

Registered services have their own, more specific overload. Any other type is reported at compile time.


[View source]