Gigitsu

Gigitsu

Ginject - A Simple, Global Injection Library for Elixir

Hi everyone!

I’d like to share a small library I’ve recently extracted from a project I’m working on: ginject.

ginject provides a minimal global injection mechanism, letting you register and inject services without plumbing extra configuration throughout your application.

Why this exists

In the app I’m developing, I needed a pragmatic way to inject alternative behaviors mainly for testing purposes.
Mox and behaviours are great — but switching implementations in test environments often requires more setup than necessary for small or isolated cases.
ginject aims to keep things lightweight and comfortable.

Part of a bigger effort

This is the first of some tools I plan to extract and publish from this project.
There are a couple more utilities in the pipeline — once cleaned up and documented — that I hope will also be useful to share with the community.

Thanks for checking it out — and I’d love to hear any feedback!

Most Liked

Asd

Asd

What do you mean? Without ginject

  @ms Application.compile_env(:app, [__MODULE__, :mapset_module], MapSet)

  def new_mapset(x) do
    @ms.new(x)
  end

And test config like

config :app, MyModule,
  mapset_module: TestMapSet

But with ginject

  use Ginject
  service MapSet, as: MS

  def new_mapset(x) do
    MS.new(x)
  end

And

config :ginject, Ginject.DI,
  strategy: Ginject.Strategy.BehaviourAsDefault,
  services: [
    {MyModule, [
      %{service: MapSet, impl: TestMapSet}
    ]}
  ]

What’s the difference?

Gigitsu

Gigitsu

With ginject, in most cases you only need two lines of configuration:

# config.exs
config :ginject, Ginject.DI, strategy: Ginject.Strategy.BehaviourAsDefault

and in test:

# test.exs
config :ginject, Ginject.DI, strategy: Ginject.Strategy.Mox

The BehaviourAsDefault strategy uses the behaviour’s own module implementation as the default service.

For example, a typical service in my project looks like this:

defmodule MyProject.ServiceA do
  @callback foo() :: any()

  @behaviour __MODULE__

  @impl true
  def foo do
    ...
  end
end

You only need to configure BehaviourAsDefault like:

services: [
  {MyModule, [
    %{service: MapSet, impl: TestMapSet}
  ]}
]

if you want a custom override for a specific service used by MyModule.

If you prefer to separate behaviour definitions from implementations, you can also define your own strategy, for example based on naming conventions.

Testing

In the test environment, the Mox strategy automatically creates mocks for you, and you can set expectations directly on them.
You can see an example here


Without ginject, you typically need to define configuration entries like:

config :app, MyModule, mapset_module: TestMapSet

for every module and every injected service.
This grows quickly in large codebases, and you must duplicate these configs in both config.exs and test.exs, plus define mock/test implementations somewhere.


I also find

service MapSet, as: MS

much easier to read and write than:

@ms Application.compile_env(:app, [__MODULE__, :mapset_module], MapSet)

and then calling:

MS.new(x)

versus:

@ms.new(x)

Additionally (though I’m not 100% certain), using module attributes may cause you to lose autocompletion and jump-to-definition features in editors.

Edit:

I realize the docs could be clearer and needs some more refinement - I’m working on it!

Gigitsu

Gigitsu

That applies only to the Mox strategy. The library itself provides dependency resolution and injection functionality, independently of Mox.

Yes. I’m considering one based on naming conventions. Other ideas are definitely welcome.

I’m not entirely sure I understand. Could you elaborate a bit more on this?

Good point, thanks for catching that. I’ll fix it as soon as possible.

As for the macro name, I like inject, but I want to think a bit more about this.

Where Next?

Popular in Announcing Top

BartOtten
This powerful library works together with Phoenix Router to provide the ultimate routing solution. It simplifies route manipulation, givi...
New
Gigitsu
Hi everyone! I’d like to share a small library I’ve recently extracted from a project I’m working on: ginject. ginject provides a minim...
New
jarlah
Testcontainers Testcontainers is an Elixir library that supports ExUnit tests, providing lightweight, throwaway instances of common datab...
New
hauleth
PhoenixBakery is library for Phoenix 1.6 (and later) that provides modules implementing Phoenix.Digester.Compressor. There are currently ...
New
Flo0807
Hello everyone! I am excited to share our heart project Backpex with you. After building several Phoenix applications, we realized that...
New
metehan
exterm_ai runs a real PTY in Elixir and exposes it in the browser using xterm.js. Previously I shared exterm library without AI this one ...
#ai
New
jallum
Turbopuffer - Elixir client for vector and full-text search I’m excited to share Turbopuffer, a new Elixir client library for the Turbop...
New
leandrocp
MDEx is a fast and extensible Markdown parser and formatter. Fast Leverage Rust to parse, manipulate and render documents using: comra...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
brainlid
LangChain is short for Language Chain. An LLM, or Large Language Model, is the “Language” part. This library makes it easier for Elixir a...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

We're in Beta

About us Mission Statement