Search code examples
rubydry-rb

How to separate registration container using Ruby dry-rb?


Are there ways to separate the registration container into multiple features as modules when exploring the dry-rb gems, particularly the auto-injector, as a newcomer to Ruby?

Here is a code sample I tried but did not work.

module SomeFeatureContainter
    extend Dry::Container::Mixin

    register "some_service" do
        SomeService.new
    end
    
end


class Container
    extend Dry::Container::Mixin
    include SomeFeatureContainter

    
end

IocResolve = Dry::AutoInject(Container)

Solution

  • In order to achieve the inversion of control, you can define a container and set the injector before invoke the service though your instantiated object.

    require 'dry-auto_inject'
    
    
    class SomeService
      # your service definition
    end
    
    module SomeFeatureContainer
      extend Dry::Container::Mixin
    
      register 'some_service' do
        SomeService.new
      end
    end
    
    class Container
      extend Dry::Container::Mixin
      configure { |config| config.auto_inject = true }
      include SomeFeatureContainer
    
      # define the injector
      IocResolve = Dry::AutoInject(self)
    end
    
    class MyClass
      include Container::IocResolve[:some_service]
    
      def use_some_service
        some_service.call
      end
    end
    
    # invoke the service with MyClass
    my_instance = MyClass.new
    my_instance.use_some_service````