Dependency Injection Simplified

Balraj Singh
techtron
Published in
5 min readNov 18, 2018

--

In our last session, we have talked about Functional ways to do error handling and looked at how this is a better way to handle errors. To achieve this we introduced some new Data Types like Optional, Try, Either. These are Functional Data Types and they helped to solve Exception/ Error handling issues. Today we will talk about simplifying DI in our app.

What is Dependency Injection?

DI is a concept which makes a class independent of its dependency management. It achieves that by decoupling the usage of an object from its creation. This helps you to follow SOLID’s dependency inversion and single responsibility principles.
To achieve this in Swift one of the most appreciated library is Swinject. This library not only provides DI but also have many other features like:-

  • Constructor/ Property/ Method Injection
  • Object Scopes as None (Transient), Graph, Container (Singleton) and Hierarchy
  • Container Hierarchy
  • Modular Components
  • Thread Safety (but the container is not thread-safe)

So we can see that this framework like many other frameworks is fully loaded. Below is a sample on how to use this library:-

// 1. Creating a IOC container & Object…

--

--

Balraj Singh
techtron

Software Engineer, Blogger, Tea Lover and Learner