bryanhuntesl

bryanhuntesl

A popular Java and C# design pattern is runtime dependency infection.
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 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?

Showing Posts 1 to 10

hauleth

hauleth

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

pablodavila

pablodavila

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

dorgan

dorgan

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

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

fireproofsocks

fireproofsocks

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:

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.

al2o3cr

al2o3cr

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:

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.

mudasobwa

mudasobwa

Creator of Cure

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

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

paulstatezny

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.

Aetherus

Aetherus

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

marcin

marcin

Freud intensifies :-))))

mathieuprog

mathieuprog

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:
config :elixir, :time_zone_database, Tz.TimeZoneDatabase

or:

Calendar.put_time_zone_database(Tz.TimeZoneDatabase)
  • by passing the module name to the different functions:
DateTime.now("America/Sao_Paulo", Tz.TimeZoneDatabase)

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 94592 917
New
cblavier
Hey there, It’s been more than a year since we started using LiveView as our main UI library and building a whole library of UI componen...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
heathen
Quite interesting article Google brought me. Didn’t find any mentions about it here. What do you think in general? Would you use togethe...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
axelson
Hi there! :wave: @frigidcode and I (but mostly him) have been running an Elixir Book club, we’re almost done with Designing Elixir Syste...
New
AstonJ
Since we have deprecated our Erlang sections (as we have dedicated Erlang Forums now) let’s add this thread for those who’d like to post ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
georgeguimaraes
Just published claude-code-elixir, a plugin marketplace for Claude Code with Elixir support. These are the plugins I’ve been using for my...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews