Skip to content

annotation Athena::DependencyInjection::Inject #

Specifies which constructor should be used for injection.

@[ADI::Register(_value: 2, public: true)]
class SomeService
  @active : Bool = false

  def initialize(value : String, @active : Bool)
    @value = value.to_i
  end

  @[ADI::Inject]
  def initialize(@value : Int32); end
end

ADI.container.some_service # => #<SomeService:0x7f51a77b1eb0 @active=false, @value=2>
SomeService.new "1", true  # => #<SomeService:0x7f51a77b1e90 @active=true, @value=1>

Without the ADI::Inject annotation, the first initializer would be used, which would fail since we are not providing a value for the active argument. ADI::Inject allows telling the service container that it should use the second constructor when registering this service. This allows a constructor overload specific to DI to be used while still allowing the type to be used outside of DI via other constructors.

Using the ADI::Inject annotation on a class method also acts a shortcut for defining a service factory.