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.

https://github.com/Gigitsu/ginject

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

Crowdhailer
Experimenting with this code. OK.try do user <- fetch_user(1) cart <- fetch_cart(1) order = checkout(cart, user) save_orde...
New
wmnnd
Hi there, for my project DBLSQD, I needed a file storage solution that is a bit more flexible than Arc. Because I thought others might f...
New
josevalim
Yes, yet another parser combinator library! Most of the parser combinators in the ecosystem are either compile-time, often using AST tra...
159 19951 141
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 30486 241
New
maltoe
Hello! Came here to announce ChromicPDF, a pet project PDF generator I’ve been working on for the past few months. Why another PDF gener...
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
kevinlang
Hey all, We have made an Ecto3 Adapter for SQLite3, ecto_sqlite3! We have successfully on-boarded the full suite of integration tests (...
New

Other popular topics Top

baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31586 112
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 49266 226
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New

We're in Beta

About us Mission Statement