IOC

Minimal dependency injection container for ruby.

Tested on the following Rubies: MRI 2.2.1, 2.0.0, 1.9.3

Installation

Add this line to your application's Gemfile:

gem 'ioc'

And then execute:

$ bundle

Or install it yourself as:

$ gem install ioc

Usage

Block Registration

This example illustrates how to register a service/component with the container by passing a block to the register method.

require "ioc"

class AccountRepository
  def initialize(database, logger)
    @database = database
    @logger = logger
  end
  # ... some store & finder methods here
end

class UserRepository
  def initialize(database, logger)
    @database = database
    @logger = logger
  end
  # ... some store & finder methods here
end

class CreateAccountService
  def initialize(, user_repository, logger)
    @account_repository = 
    @user_repository = user_repository
    @logger = logger
  end

  def call(req, res)
    # ... create account code
  end
end

# Register Services
container = IOC::Container.new
container.register(:create_account_service) do |c|
  CreateAccountService.new(c., c.user_repository, c.logger)
end
container.register(:user_repository) do |c|
  UserRepository.new(c.database, c.logger)
end
container.register(:account_repository) do |c|
  AccountRepository.new(c.database, c.logger)
end
container.register(:logger){|c| Logger.new}
container.register(:database){|c| DB}

# Resolve Service
container.resolve(:create_account_service).call(req, res)

# Release the object graph for garbage collection
container.release

Automatic Dependency Resolution

Rather than assigning each service's dependencies manually like in the example above, we can allow the container to build and inject each service's dependencies automatically.

# Register Services
container = IOC::Container.new
container.register(:create_account_service, CreateAccountService)
container.register(:user_repository, UserRepository)
container.register(:account_repository, AccountRepository)
container.register(:logger){|c| Logger.new}
container.register(:database){|c| DB}

# Resolve Service
container.resolve(:create_account_service).call(req, res)

# Release the object graph for garbage collection
container.release

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request