Getting Started with Zenject

Zenject is a lightweight Dependency Injection framework that was created just for Unity.

Dependency Injection (DI) is a design pattern whereby one object supplies the dependencies of another object.

Typically, this is accomplished by a container that has knowledge of every dependency in the project.

As a result, the codebase becomes an amalgamation of disjointed parts that are glued together at runtime.

This style of code design is easier to maintain, understand, and test. It also adheres to the 5 principles that make up the SOLID design principles.

Zenject Logo

The Zenject Framework

Zenject was created out of a need for a DI framework that was compatible with Unity.

Since it’s creation, other DI frameworks that have popped up on the Asset Store. Nonetheless, Zenject has remained one of the most popular.

This is most likely due to it’s roots in Ninject, which is a .Net DI framework that boasts an obsessive focus on simplicity and ease of use.

The Zenject framework is available for download on GitHub, or through Unity’s Asset Store. And installation is as simple as dragging the main folder into your project.

Once you’ve imported the framework into your project you’ll have access to 2 games that can be referenced as examples of real world usage.

A Simple Zenject Example

In this tutorial, we’ll be injecting an interface called IAudioService.

Initially, each class that depends on IAudioService creates its own instance of AudioService.

But this can become a maintenance nightmare when we need to use a different implementation of IAudioService. We’d need to manually update instantiation of AudioService.

So instead we’ll add IAudioService to the constructor of each class that needs it. Then we’ll create an installer that knows how to instantiate and inject the correct instance.

By the end you should be ready to add Dependency Injection to your own project using this powerful framework.