2. AttrInject
2.1. Overview
AttrInject is an implementation of dependency injection that uses declared interfaces to determine dependencies. It is based on an implementation by Christian Neukirchen at http://rafb.net/paste/results/sexpfu84.html.
2.2. Usage
AttrInject is very straightforward to use. Just require the AttrInject library in every service implementation and use the new attr_inject
macro to specify which other services the class depends on:
require 'needle/extras/attr-inject' class Foo attr_inject :bar attr_inject :baz, :blah def frobnicate @bar + @baz / @blah end end
The attr_inject
macro does not create any accessors—it only declares the dependencies that the corresponding service has. Then, when you register the service, you specify one of the inject
service models:
require 'needle' require 'needle/extras' ... reg.require_library 'needle/extras' reg.define do |b| b.bar { 5 } b.baz { 10 } b.blah { Math::PI } b.foo( :model => :singleton_inject ) { Foo.new } end
The singleton_inject
service model is just like singleton
, but it will also automatically inject all of the declared dependencies into the new service. Thus, invoking #frobnicate
on the foo
service would compute and return (in this case) 5 + 10 / PI
.
This approach has the benefit of reducing the amount of initialization code you have to write. On the other hand, it more tightly couples your implementation code to Needle itself.