Using dry-system auto-registration with singletons


#1

I’m trying to use the dry-system auto-registration to create some objects that “should” be singletons, though I don’t want to force them to be at a code level. For example I might have some sort of domain-aware cache that I want to have injected, and every time it gets injected it should have the same underlying object.

If I have a trivial object that exposes #h as a Hash and make that auto-registered, I can readily see that the data isn’t getting shared, like

Application[:component].h[:k] = :v
v = Application[:component].h[:k]
print v ? v : "[nil]"

(Complete example at https://gist.github.com/dmaze/1cb828a47045b2214a1491fc34cb6144)

Is there a convenient way to make the auto-registrar provide a single instance of the object to all consumers, instead of having it get recreated on every call?


#2

The simplest way right now would be to register the object in a bootable component, e.g. boot/my_cache.rb:

MyApp::Container.boot :my_cache do
  start do
    require "my_cache"

    register "my_cache", MyCache.new
  end
end