I’ve just started experimenting with dependency injection in an existing Rails app.
The idea is to incrementally convert more code to use dependency injection.
For that I am using dry-rails gem and auto registration in particular
Here are my questions:
- How do I have multiple separate containers in the same rails app ?
This is needed in order to create clear separation between different domains of my application.
- Is there an option to integrate dry-system into rails without dry-rails ?
dry-rails introduces other features and dependencies that I don’t need for DI containers. However dry-rails provides seamless integration with rails which I need. Probably I was looking for a slim version of dry-rails.
- Is there an option to register only classes from some specific folders under “/lib” instead of the whole “/lib” folder ?
I’ve tried in my rails application called “Athena”:
# config/initializers/system.rb
Dry::Rails.container do
auto_register!("app/domain")
auto_register!("lib/callbacks")
end
Folder structure is:
/app
/domain
/callbacks
/use_case
callback_create_command.rb
/lib
/callbacks
callback_repository.rb
/test_helpers
Classes:
# /lib/callbacks/callback_repository.rb
module Callbacks
class CallbackRepository
end
end
# /app/domain/callbacks/use_case/callback_create_command.rb
module Callbacks
module UseCase
class CallbackCreateCommand
include Athena::Deps[:callback_repository]
end
end
This fails “bin/rails console”.
“Dry::System::FileNotFoundError: could not resolve require file for callbacks.callback_repository”
During wrong configuration of container “bin/rails console” may take very long to even start printing anything to console. Sometimes it does not return at all after more than a minute. I had to close the terminal window altogether and open a new one. Or interrupt the console with Ctrl+C.