DI (resolve v0.0.1)
Dependency injection
usage
Usage
Include DI in the module that requires dependency injection with use DI
.
Any place in that module that might need a dependency injected can then use
di(<module>)
to allow another module to be injected. The module passed to
di/1
will be used if another module isn't injected.
defmodule MyInterface do
use DI
def some_command, do: di(__MODULE__).some_command
end
configuration
Configuration
DI can be configured in the project's config.exs
.
Opts
compile
- (false) - Sets the mappings at compile time and doesn't start the process that allows them to be modified at runtime. This method is more secure and more performant. Compiling is intended for production and runtime is intended for unit tests.mappings
-[]
- A two element tuple of the modules to map from and to:{from, to}
Example
config :<app>, di: %{
compile: true,
mappings: [
{OriginalModule, InjectedModule},
]
}
runtime
Runtime
Dependencies can be injected at runtime with inject/2
. This is intended for
unit testing, but not necessarily limited to it. Runtime mappings will be
less performant compared to compiled mappings, as each lookup goes through
a read-optimized ETS table.
DI.inject(OriginalModule, InjectedModule)
Modules can also be defined directly in a block, which can be helpful if they are only needed for certain tests.
DI.inject(Port, quote do
def open(_name, _opts), do: self()
def close(_port), do: :ok
def command(_port, _data), do: :ok
end)
Link to this section Summary
Functions
Flag a module as eligible for dependency injection.
Inject a module in place of another one.
Revert this dependency to the original module.
Link to this section Functions
di(module)
Flag a module as eligible for dependency injection.
Defaults to module
unless a new dependency is injected in its place.
inject(target_module, injected_module)
Inject a module in place of another one.
revert(module)
Revert this dependency to the original module.
This function is idempotent and will not fail if DI already points to the original module.