# Dependency injection/IOC

**URL:** <https://forum.elixirforum.com/t/dependency-injection-ioc/39496>\
**Category:** Discussions\
**Tags:** java, design-patterns\
**Created:** [May 7, 2021, 10:16pm UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496 "2021-05-07T22:16:54Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![bryanhuntesl](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/bryanhuntesl/32/8270_2.png) [@bryanhuntesl](https://forum.elixirforum.com/u/bryanhuntesl)\
**Post date:** [May 7, 2021, 10:16pm UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/1 "2021-05-07T22:16:54Z")

</div>

A popular Java and C# design pattern is [runtime dependency infection](https://en.m.wikipedia.org/wiki/Dependency_injection).  
People tend to associate it with Object Oriented programming but there is nothing inherent to OOP.

Runtime dependency injection/resolution can work for any system that provides a runtime mechanism to override or modify the version of a class or module which has been requested.

It strikes me that [Mox](https://github.com/dashbitco/mox) provides a limited form of dependency injection in that sense.

Now I’m not advocating for it, but just for the sake of idle discussion (and I do know about Application.env and regular configuration stuff) has anyone ever attempted bringing Java style DI to Elixir?

---

<div class="post-metadata">

**Author:** ![hauleth](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/hauleth/32/18942_2.png) [@hauleth](https://forum.elixirforum.com/u/hauleth)\
**Post date:** [May 7, 2021, 10:20pm UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/2 "2021-05-07T22:20:37Z")

</div>

I just pass modules as a function arguments where needed. In other cases I just do not bother at all.

---

<div class="post-metadata">

**Author:** ![pablodavila](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/pablodavila/32/21840_2.png) [@pablodavila](https://forum.elixirforum.com/u/pablodavila)\
**Post date:** [May 7, 2021, 10:33pm UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/3 "2021-05-07T22:33:12Z")

</div>

In which cases would you pass a module as an argument? Do you mean a module when it’s a GenServer?

---

<div class="post-metadata">

**Author:** ![dorgan](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/dorgan/32/22107_2.png) [@dorgan](https://forum.elixirforum.com/u/dorgan)\
**Post date:** [May 7, 2021, 10:38pm UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/4 "2021-05-07T22:38:39Z")

</div>

I think an example of this would be Ecto. In cases like `Ecto.Multi`, the repo module is passed around so you can make sure you’re using the same repo during a transaction: [Ecto.Multi — Ecto v3.14.0](https://hexdocs.pm/ecto/Ecto.Multi.html#run/3)

A case where I did that was when doing something similar to the strategy pattern, I had many modules that were candidates to perform a given action, and when one of them was picked, I passed them around to the functions that would use it

---

<div class="post-metadata">

**Author:** ![fireproofsocks](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/fireproofsocks/32/7669_2.png) [@fireproofsocks](https://forum.elixirforum.com/u/fireproofsocks)\
**Post date:** [May 8, 2021, 12:19am UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/5 "2021-05-08T00:19:17Z")

</div>

For sure I do this: if you want to achieve testable code, it’s quite handy to be able to “inject” overrides as options. E.g. something like the following:

```elixir
def fetch_page(url, opts \\ []) do
    parser = Keyword.get(opts, :parser, SomeParserModule)
    client = Keyword.get(opts, :client, HTTPoison)
    with {:ok, raw_html} <- client.get(url), 
        {:ok, parsed} <- parser.parse(raw_html) do
        {:ok, struct(SomeStruct, parsed)}
    end
end

```

This is over-simplified, perhaps, but if you don’t want to redundantly test a separate module that receives dispatches, then providing an injectable/overridable option lets you focus on one layer/module at a time.

Some purists may argue that this isn’t the same as DI, but it accomplishes the same goals and has the same intent as far as I’m concerned. Mox is certainly helpful in this regard, but it’s not strictly required.

---

<div class="post-metadata">

**Author:** ![al2o3cr](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/al2o3cr/32/3457_2.png) [@al2o3cr](https://forum.elixirforum.com/u/al2o3cr)\
**Post date:** [May 8, 2021, 1:15am UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/6 "2021-05-08T01:15:18Z")

</div>

Beware that this approach converts compile-time errors (like passing the wrong number of arguments to a function) to runtime errors, and substantially reduces the usefulness of Dialyzer.

Wrapping the call can help some:

```elixir
def fetch_page(url, opts \\ []) do
  with {:ok, raw_html} <- client_get(url, opts),
  ...
end

@spec client_get(String.t(), Keyword.t()) :: {:ok, String.t()} | {:error, any()}
defp client_get(url, opts) do
  client = Keyword.get(opts, :client, HTTPoison)
  client.get(url)
end

```

This allows Dialyzer to understand the type of `client_get` - but there is no checking that the type written in the `@spec` matches the types actually seen at runtime.

---

<div class="post-metadata">

**Author:** ![mudasobwa](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/mudasobwa/32/41119_2.png) [@mudasobwa](https://forum.elixirforum.com/u/mudasobwa)\
**Post date:** [May 8, 2021, 5:55am UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/7 "2021-05-08T05:55:27Z")

</div>

Usually, we have a `Client` behaviour here, declaring a type, and refine the spec to

```elixir
@typet opts [{:client, Client.t()} | {atom(), any()}]
@spec client_get(String.t(), opts()) :: {:ok, String.t()} | {:error, any()}

```

---

<div class="post-metadata">

**Author:** ![paulstatezny](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/paulstatezny/32/18204_2.png) [@paulstatezny](https://forum.elixirforum.com/u/paulstatezny)\
**Post date:** [May 8, 2021, 7:05am UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/8 "2021-05-08T07:05:13Z")

</div>

There are libraries that have different “adapters” for use in production, development, and test environments. This is sort of similar to dependency injection.

Take the Swoosh hex library for sending emails. You set the adapter (a module that follows a behaviour) in configuration. In production, you choose an adapter corresponding to your email service — say, the SendGrid adapter. In test, you use the Test adapter which is wired up to allow you to perform assertions on whether an email was sent and if it contained the right data. In development, you use a special adapter that captures “sent emails” in memory in a process, so that you can go to a special local route and view what _would_ have been sent were it production.

---

<div class="post-metadata">

**Author:** ![Aetherus](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/aetherus/32/17203_2.png) [@Aetherus](https://forum.elixirforum.com/u/Aetherus)\
**Post date:** [May 8, 2021, 7:09am UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/9 "2021-05-08T07:09:39Z")

</div>

I think this is a problem of how to ensure the passed-in module has the expected `@behaviour` using typespec.

---

<div class="post-metadata">

**Author:** ![marcin](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/marcin/32/24679_2.png) [@marcin](https://forum.elixirforum.com/u/marcin)\
**Post date:** [May 8, 2021, 7:25am UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/10 "2021-05-08T07:25:20Z")

</div>

> [@bryanhuntesl](#):
>
> A popular Java and C# design pattern is [runtime dependency infection](https://en.m.wikipedia.org/wiki/Dependency_injection).

Freud intensifies :-))))

---

<div class="post-metadata">

**Author:** ![mathieuprog](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/mathieuprog/32/16860_2.png) [@mathieuprog](https://forum.elixirforum.com/u/mathieuprog)\
**Post date:** [May 8, 2021, 3:48pm UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/11 "2021-05-08T15:48:35Z")

</div>

I was a fan of dependency injection containers when I was working with object-oriented web frameworks. Alternatives were a service locator or a global registry/singleton, which were both considered anti-patterns. When you work with a DI container, your classes typically keep the dependencies as state in the constructors.  
In Elixir we just don’t need those anymore, it’s a just a different way of thinking and designing. We use config and functions arguments.

Even though the OP didn’t mention containers, I believe dependency injection is more talked about in OOP because it is harder to achieve.

And as an example of how DI is achieved in Elixir, take the injection of a time zone database to `DateTime` functions:

- via configuration:

```elixir
config :elixir, :time_zone_database, Tz.TimeZoneDatabase

```

or:

```elixir
Calendar.put_time_zone_database(Tz.TimeZoneDatabase)

```

- by passing the module name to the different functions:

```elixir
DateTime.now("America/Sao_Paulo", Tz.TimeZoneDatabase)

```

---

<div class="post-metadata">

**Author:** ![LostKobrakai](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/lostkobrakai/32/3072_2.png) [@LostKobrakai](https://forum.elixirforum.com/u/LostKobrakai)\
**Post date:** [May 8, 2021, 4:07pm UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/12 "2021-05-08T16:07:29Z")

</div>

> [@mathieuprog](#):
>
> And as an example of how DI is achieved in Elixir, take the injection of a time zone database to `DateTime` functions:
> 
> - via configuration:
> 
> ```elixir
> config :elixir, :time_zone_database, Tz.TimeZoneDatabase
> 
> ```
> 
> or:
> 
> ```elixir
> Calendar.put_time_zone_database(Tz.TimeZoneDatabase)
> 
> ```
> 
> - by passing the module name to the different functions:
> 
> ```elixir
> DateTime.now("America/Sao_Paulo", Tz.TimeZoneDatabase)
> 
> ```

To be fair this is using the app env for storage and is therefore a singleton acting as a global registry.

GenServers keep the callback module in the process state – and even the callback module might maintain dependencies passed at the start via the process state – which is not too different from constructor based DI in OOP.

Yes, in elixir we might not need dedicated libraries, given we have different tools for maintaining state, but the general approaches are kinda the same.

---

<div class="post-metadata">

**Author:** ![paulstatezny](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/paulstatezny/32/18204_2.png) [@paulstatezny](https://forum.elixirforum.com/u/paulstatezny)\
**Post date:** [May 8, 2021, 10:19pm UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/13 "2021-05-08T22:19:03Z")

</div>

> I was a fan of dependency injection containers when I was working with object-oriented web frameworks.

I was too, until I spent years of my life diligently writing unit tests, only to realize years later that those tests proved very little about the codebase.

Dependency injection is evangelized because it makes it easier to unit test with mocks.

Integration tests are vital. Unit tests are mostly useful for pure functions. Mocks lead to false confidence about the test suite.

When I came to Elixirland and learned to write mostly integration tests, I was blown away by the amount of real bugs the test suite caught.

---

<div class="post-metadata">

**Author:** ![bryanhuntesl](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/bryanhuntesl/32/8270_2.png) [@bryanhuntesl](https://forum.elixirforum.com/u/bryanhuntesl)\
**Post date:** [May 11, 2021, 9:10am UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/14 "2021-05-11T09:10:44Z")

</div>

Haha, too much time explaining the downsides of `binary_to_term` that day 🤪

---

<div class="post-metadata">

**Author:** ![bryanhuntesl](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/bryanhuntesl/32/8270_2.png) [@bryanhuntesl](https://forum.elixirforum.com/u/bryanhuntesl)\
**Post date:** [May 11, 2021, 9:12am UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/15 "2021-05-11T09:12:20Z")

</div>

Great answers everyone, thanks for the thoughtful replies.

---

<div class="post-metadata">

**Author:** ![kenny-evitt](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/k/e47774/32.png) [@kenny-evitt](https://forum.elixirforum.com/u/kenny-evitt)\
**Post date:** [May 14, 2021, 5:07pm UTC](https://forum.elixirforum.com/t/dependency-injection-ioc/39496/16 "2021-05-14T17:07:35Z")

</div>

You _can_ do it anywhere. It’s a pretty helpful pattern for, e.g. testing API clients – use the ‘web client’ for production/staging (and maybe dev too), and a ‘test client’ for (unit) tests.

A functionally similar kind of thing is to retrieve a module name from config during compilation (by storing it in a module attribute). That’s a little less flexible than just passing a module as an argument.
