Sign in

MoDI — lightweight IoC container for Unity

Once I decided to figure out how to work with Zenject and Ninject in Unity. Made several test projects — it seems to work. I started digging further, understood the principle and decided that I wanted my own, but simpler :) So MoDI appeared.

MoDI is a lightweight IoC container developed specifically to use with Unity. It’s inspired by Zenject, but not so complex. Just one more bicycle for binding types, instances, resolving them and injection into fields 🙃

To start use MoDI you shouldn’t call any initialize methods. When you first call DI.Get() then MoDI already initialized and ready to work. Just add using MoDI; to your scripts and go ahead.

Call DI.Get() to get default container. Pass container tag into Get("my_container") method to return custom container.

Call DI.Get().Bind<YourType>() to make bind in container. Your can combine builder methods in chain: DI.Get().Bind<YourType>().WithId("id1").AsSingle().

To resolve object from container call DI.Get().Resolve<YourType>().

To mark field for injection set [Inject] attribute to it.

Simplest example:

using MoDI;
using UnityEngine;
public class QuickStart : MonoBehaviour { public void Start() {
DI.Get().Bind<Hello>().WithArguments("Hi, I'm MoDI!");
Hello hello = DI.Get().Resolve<Hello>();
}

}
public class Hello { public Hello(string data) {
Debug.Log(data);
}
}

After run this script you can see Hi, I'm MoDI! message in console.

You can find more examples and API descriptions in the documentation.

Made for myself, but maybe someone will be interested. If you want to develop in this like me, write, I will help you in any way I can 😉

This article is translation from my blog: https://mopsicus.ru. I will try to translate and write here more often if you like post as this.