Dependency injection

suggest change

Dependency Injection (DI) is a software design pattern where an object receives its dependencies (collaborating services, clients, or repositories) from an external source rather than creating them directly inside its own methods using Class.new.

In Ruby, dependency injection promotes loose coupling and simplifies unit testing by eliminating the need to monkey-patch classes or use brittle global test stubs.

The Problem: Hardcoded Dependencies

When a class instantiates its own dependencies directly, it cannot be tested in isolation without triggering real side effects (like sending emails or connecting to external APIs):

class UserRegistration
  def register(user_data)
    user = User.create(user_data)

    # Hardcoded dependency: tightly coupled to production EmailService
    mailer = EmailService.new
    mailer.send_welcome_email(user.email)

    user
  end
end

Testing UserRegistration will either send real emails or require fragile monkey-patching like allow_any_instance_of(EmailService).to receive(:send_welcome_email).

Idiomatic Ruby: Constructor Injection with Default Values

The most common and lightweight way to implement dependency injection in Ruby is to pass collaborators into the constructor using keyword arguments with sensible defaults:

require 'logger'

class EmailService
  def send_welcome(email)
    puts "Sending welcome email to #{email}"
  end
end

class UserRegistration
  attr_reader :mailer, :logger

  # Dependencies are injected via initialize with production defaults
  def initialize(mailer: EmailService.new, logger: Logger.new($stdout))
    @mailer = mailer
    @logger = logger
  end

  def register(email)
    @logger.info("Registering user: #{email}")
    @mailer.send_welcome(email)
    { status: :ok, email: email }
  end
end

Production Usage

Callers do not need to supply dependencies explicitly:

service = UserRegistration.new
service.register("alice@example.com")

Unit Testing Usage

In test suites (such as RSpec or Minitest), pass a simple test double or fake object without touching the production network:

class FakeEmailService
  attr_reader :sent_emails

  def initialize
    @sent_emails = []
  end

  def send_welcome(email)
    @sent_emails << email
  end
end

# Testing in isolation
fake_mailer = FakeEmailService.new
null_logger = Logger.new(nil) # Discard log output in tests

registration = UserRegistration.new(mailer: fake_mailer, logger: null_logger)
registration.register("test@example.com")

raise "Failed!" unless fake_mailer.sent_emails == ["test@example.com"]
puts "Test passed!"

Container-Based DI with dry-container and dry-auto_inject

For large-scale architectures and frameworks like Hanami 2, the dry-rb ecosystem provides formal dependency containers and auto-injection:

require 'dry-container'
require 'dry-auto_inject'

# 1. Define application container
class AppContainer
  extend Dry::Container::Mixin

  register('repositories.user') { UserRepository.new }
  register('services.sms')      { TwilioSmsService.new }
end

# 2. Build injection module
Import = Dry::AutoInject(AppContainer)

# 3. Auto-inject dependencies into services
class NotifyUser
  # Injects 'services.sms' as `sms` and 'repositories.user' as `user_repo`
  include Import['services.sms', user_repo: 'repositories.user']

  def call(user_id, message)
    user = user_repo.find(user_id)
    sms.send_message(user.phone, message)
  end
end

Summary of Benefits

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents