Inject — Dependency injection library for Swift with support for Singletons

Daniel Illescas
Analytics Vidhya
Published in
3 min readMay 23, 2020
Example of “Inject” for Swift

Hello everyone, inspired by a recent article here at medium and some practice with dependency injection on ASP.NET I though I would like create a small library to ease dependency injection for Swift (including iOS, macOS, etc).

The idea

First, this is an example at how is natively implemented on ASP.NET core on C#:

Dependency injection on ASP.NET

Really easy, right? You just add the types you want to inject and later on you create a constructor that accepts that type and you just have it.

There are a few ways and options when doing that, including adding singletons too, but that’s the idea.

Implementation on Swift — Inject

To implement in on Swift, the first thing is to store your dependencies, like we previously saw. I internally use a dictionary which keys are a type and the value is a function that builds the wanted value. This is all done in a “Dependency resolver”; we need to instantiate a static value of that type on our app first:

Dependency injection resolvers

Then the first thing you app need to do is add the dependencies. In this case we are using a protocol and a value that implements that protocol:

Adding dependencies — Inject

This is how we are going to inject the dependency in our code wich Inject . First you need to pass a dependency resolver to it, so it can internally look up for how to build the desired type.

To use the injected value you just need to use the property as if it was any other property, you can also change its value so it uses a specific one instead of the injected value.

Inject init and how to use it

In practice, you will want to avoid passing the resolver all the time, so you can locally create this extension:

Useful extension for Inject

Usage

This is a full example of a class that uses an injected value.

Full example of Inject usage

That’ts the recommended way of using Inject. You create your properties, then a constructor that accepts an optional dependency and finally you assign that to your self property. By doing this, if you pass nil it will use the injected value, but if you pass a valid value it will use that instead.

As you’ve seeen this library also supports singletons, the usage is the same but the internal behavious is a bit differente, for singletons we save a lazy variable with its value that will be used across your app.

More

You can use this library right now by importing the swift package: https://github.com/illescasDaniel/Inject-Swift.git

For more information and examples I created an example project:

And this is the official Inject repo:

Thanks for reading this article!

--

--