Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
DIM - Dependency Injection - Minimal
branch: master

This branch is 12 commits ahead, 4 commits behind jimweirich:master


DIM: Dependency Injection - Minimal

DIM is Jim Weirich's minimalistic dependency injection framework, maintained in gem form by Mike Subelsky.

Dependency injection lets you organize all of your app's object setup code in one place by creating a container. Whenver an object in your application needs access to another object or resource, it asks the container to provide it (using lazily-evaluated code blocks).

When testing your code, you can either stub out services on the container, or you can provide a substitute container.


The following could be in a "lib.init.rb" file or in a Rails app, "config/initializers/container.rb":

require "dim"
require "logger"
require 'game'
require 'event_handler'
require 'transmitter'

ServerContainer =

ServerContainer.register(:transmitter) { |c| }

ServerContainer.register(:event_handler) do |c|
  eh =
  eh.transmitter = c.transmitter
  eh.logger = c.logger

ServerContainer.register(:listening_host) { "" }
ServerContainer.register(:listening_port) { "8080" }

ServerContainer.register(:game) do |c|
  game =
  game.logger = c.logger
  game.event_handler = c.event_handler = c.listening_host
  game.port = c.listening_port

ServerContainer.register(:root_dir) do |c| + "/.."))

ServerContainer.register(:log_file_path) do |c|

ServerContainer.register(:logger) do |c|

# attempts to read ENV["API_PASSWORD"], otherwise makes sure that the parent container has
# a service named api_password registered

Using the above code elsewhere in the app, when you want a reference to the app's logger object:"I didn't have to setup my own logger")

Or if you wanted access to the game instance created during setup (which already is configured with everything it needs):

current_game =

If you don't like creating even the one dependency on the global constant ServerContainer, you could inject ServerContainer itself into your objects like so:

More Background

Jim wrote a nice article explaining the rationale for this code and how it works. Also check out his slides.


Dim is available under the MIT license (see the file LICENSE for details).

Something went wrong with that request. Please try again.