Circular dependencies using plain dry-container + dry-autoinject

Hello, everyone!

I’m experimenting with container and auto_inject gems. I’ve build a very simple application called url_shortener and tried to organize everything with functional objects and container. As you can see I’m into some kind of a circular dependency here and I have to require components in a strictly defined order. Besides, I have to reassign the constant Import before every require_relative, because Ruby won’t find Import while require_relative other component.

I guess, I just do not understand completely the way I should use container :slight_smile:. And my question is how to organize dependencies to use the same aliases I’m using?

I’ve been considering the possibility to use dry-system and create smth like this, but failed to find the way to create aliases:

class Application < Dry::System::Container
  configure do |config|
    config.root = Pathname('./my/app')

    # we set 'lib' relative to `root` as a path which contains class definitions
    # that can be auto-registered
    config.auto_register 'lib', 'persistence', 'operatons'
  end

  load_paths!('lib', 'persistence', 'operatons')

  # HERE I WOULD CREATE MY DEPENDENCIES' ALIASES
  alias_dependency "validate", "operations.url.validations.validate"
  alias_dependency "storage", "persistence.storage"
end

I saw Berg example of using container and as I can see it’s not exactly what I wanna have here.

Hi @raventid

You need to define your container before your code has been loaded. This means you need to put all your require/require_relative to registration blocks, like this

Container.register("algorithm") do 
  # Possible bidirectional algorithms
  require_relative '../../lib/algorithms/revertable/bijective'
  # Possible one-direction algorithms
  require_relative '../../lib/algorithms/hashing/random_string'
  Shortener::Algorithm::RandomString.new
end

And you need to assign Import just once, at the very bottom of container.rb

1 Like

I rewrote my container this way and it solved all of my problems! Thank you!

The only problem now is that I don’t understand how container loads my dependencies))) And I can’t tell is it reinitialize my DB connection or not. But I’ll try to read the source code to answer my questions, thank you one more time, I’m happy now :slight_smile: