2.6. Dependency Injection

Dependency Injection of S2Container.Ruby is property injection. Instance variables and accessor methods are treated as a property. By an instance variable property, the component which will be injected is specified by the default value of a property. When a property value is nil, a property name (Symbol) is used as a component name. When a property value is Array and the 1st value is ":di", then the 2nd value is used as a component name. By an accessor method property, the component which will be injected is specified by the name specified by attr_accessor method.

require 's2container'

class Action
  s2comp
  def initialize
    @a = nil                # name of component is a ":a"
    @b = :di, ServiceB       # specified by Array
  end
  attr_reader :a, :b
  attr_accessor :c
end

class ServiceA
  s2comp :name => :a
end

class ServiceB
  s2comp :instance => :prototype
end

class ServiceC
  s2comp :name => :c
end

p s2app[Action].a
p s2app[Action].b
p s2app[Action].c
[Note]NOTE

This Example is located at "examples/quickstart/quickstart6".



© Copyright The Seasar Foundation and the others 2008-2009, all rights reserved.