Sha256: 77c4f7544407416859ade4cbb725d2b955d28da19519d291640bf54e8103d2cb

Contents?: true

Size: 1.85 KB

Versions: 4

Compression:

Stored size: 1.85 KB

Contents

Registering services with a Needle registry is very straightforward. The simplest way to do it is:

<pre>
  registry.register( :foo ) { Bar.new }
</pre>

The above will register a new service with the registry, naming it @:foo@. When @:foo@ is requested from the registry, a new instance of @Bar@ will be instantiated and returned.

You get services from the registry in either of two ways:

<pre>
  # Treating the registry as a Hash
  svc = registry[:foo]

  # Treating the service as a property of the registry
  svc = registry.foo
</pre>

h3. Convenience Methods

Because you will often need to register many services with a registry at once, two convenience methods have been provided to make this use case lean and mean.

The first is @define@. Just pass a block to define that accepts one parameter. This parameter will be a "builder" object that allows you to define services just by sending them as messages to the builder:

<pre>
  registry.define do |b|
    b.foo { Bar.new }
    b.bar { Foo.new }
    ...
  end
</pre>

Alternative, you can call @define!@, passing a block that accepts no parameters. This block will be evaluated in the "builder" object's context, with any unrecognized method call being interpreted as a new service registration of that name:

<pre>
  registry.define! do
    foo { Bar.new }
    bar { Foo.new }
    ...
  end
</pre>

Both of the above will register two new services with the registry, @:foo@ and @:bar@.

h3. Default Lifecycle

By default, a service is only instantiated once per registry. This means that (using the above example) if the service @:foo@ were queried twice, the registry would return the same object for both queries:

<pre>
  svc1 = registry.foo
  svc2 = registry.foo

  p svc1.object_id == svc2.object_id #=> true
</pre>

You can change this behavior, with _service models_. See the chapter on Service Models for more information.

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
needle-0.6.0 doc/manual/parts/02_services.txt
needle-0.9.0 doc/manual/parts/02_services.txt
needle-1.0.0 doc/manual/parts/02_services.txt
needle-1.1.0 doc/manual/parts/02_services.txt