Skip to content

Repository files navigation

DIM: Dependency Injection - Minimal

Gem VersionBuild StatusLicense: CC BY 4.0

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.

Example

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=Dim::Container.newServerContainer.register(:transmitter){ |c| Transmitter.new(c.logger)}ServerContainer.register(:event_handler)do |c|
eh=EventHandler.neweh.transmitter=c.transmittereh.logger=c.loggerehendServerContainer.register(:listening_host){"0.0.0.0"}ServerContainer.register(:listening_port){"8080"}ServerContainer.register(:game)do |c|
game=Game.newgame.logger=c.loggergame.event_handler=c.event_handlergame.host=c.listening_hostgame.port=c.listening_portgameendServerContainer.register(:root_dir)do |c|
Pathname.new(File.expand_path(File.dirname(__FILE__) + "/.."))endServerContainer.register(:log_file_path)do |c|
"#{c.root_dir}/log/#{c.environment}.log"endServerContainer.register(:logger)do |c|
Logger.new(c.log_file_path)end# attempts to read ENV["API_PASSWORD"], otherwise makes sure that the parent container has# a service named api_password registeredServerContainer.register_env(:api_password)

Using the above code elsewhere in the app, when you want a reference to the app's logger object:

ServerContainer.logger.info("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=ServerContainer.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:

World.new(GameContainer)

More Background

Jim wrote a nice article explaining the rationale for this code and how it works. At least two other implementations of the code have been created:

Documentation

Available at rubydoc.info.

License

Attribution-ShareAlike 4.0 International (CC BY-SA 4.0). See LICENSE for full text.

About

Minimalist dependency injection framework based on a blog post by Jim Weirich (RIP)

Topics

Resources

Stars

21 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages