Last active
March 5, 2017 19:19
-
-
Save hrom512/48af4edf8bfbc3a9cb2992ed65e11dc2 to your computer and use it in GitHub Desktop.
Dependency Injection example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Source: https://discuss.dry-rb.org/t/examples-of-how-to-use-dry-container-dry-auto-inject/82/9 | |
| require 'dry-container' | |
| require 'dry-auto_inject' | |
| module Api | |
| def self.configure | |
| container.register :main_component, -> { MainComponent.new } | |
| container.register :dependency, -> { Dependency.new } | |
| container.freeze | |
| end | |
| def self.try_dry_rb_container | |
| container.resolve(:main_component).hello_world | |
| end | |
| private | |
| @@container = Dry::Container.new | |
| AutoInject = Dry::AutoInject(@@container) | |
| def self.container | |
| @@container | |
| end | |
| end | |
| class MainComponent | |
| include Api::AutoInject[:dependency] | |
| def hello_world | |
| dependency.say_hi | |
| end | |
| end | |
| class Dependency | |
| def say_hi | |
| "Hi from dry-rb dry-container injected with dry-auto-inject" | |
| end | |
| end | |
| Api.configure | |
| puts Api.try_dry_rb_container |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment