Inversion of Control with Unity3D – part 2

In my previous article, I briefly introduced the problems related to inject dependencies using the Unity 3D Framework. I did not give an in depth explanation because only those who understood the problem by themselves, can really understand why a solution is needed. Contrarily you may think that all this theory is irrelevant as long as “things get done”…well this can co28142879[1]me as a shock to you, but in a big team/complex project environment, is actually important how things get done too. Getting things done for the sake of finishing them as soon as possible, may lead to some tragic consequences. Have you ever seen memes about the css !important value? With it you can surely get your CSS done, but then your team would not really be able to maintain or extend the css anymore. The truth is that keeping your code maintainable is as important as getting things done since, for large projects, the long term cost of maintainability is much higher than the cost of developing features.Cjg9a5ZWgAAPTcS[1]

Completing a feature in two days and then spending five days to fix the relative bugs found in production, due to the complexity of the solution adopted, won’t make you look good. Breaking good design practices to complete a feature in record time and then forcing someone else to spend several days to refactor it in order to extend its functionalities, won’t make you look good.

I spent a long time, during my carrier, to understand how to write maintainable code and I eventually realised that the most important condition is to write simple code, so simple that doesn’t even need to be commented to be clearly understood by another coder. Writing simple code isn’t an easy task, often, in fact, who thinks to get things done easily, ends up writing very convoluted code, hard to read, maintain and refactor.  I also realised that the only way to be able to write simple code for each possible problem is to deeply understand all the aspects involved in good code design.

These aspects are fundamentally explained in the SOLID principles, principles that I will mention several times in my articles. Being able to inject dependencies efficiently plays a key role and that’s why I eventually decided to implement an IoC container.

Before to discuss the example I built on purpose to show the features of my IoC container, I want to share my experience with other IoC containers I used before to write mine. As game developer, the Inversion of Control concept was unknown to me, although I surely used IoC without knowing what it was and what it was called.

My experience with other IoC containers

When I was introduced to the concept of Dependency Injection and all the problems related to it, the IoC containers were (and still are) extensively used to ease the coders work. That’s why, when I shifted from traditional procedural C++ programming to event based coding in Actionscript, I started to use Robotlegs. Robotlegs is an IoC Container for the actionscript language.

After I used it for a couple of small personal projects, I decided to abandon it. This is because eventually I ended up convincing myself that manual Dependency Injection was a better practice. However after some time, when I moved to C#, I started to experiment with Ninject and after discussing the practices with its author, I realised that I was not appreciating the use of an IoC container because I did not understand its principles.

To understand the principles, we need to introduce some concepts first:

Composition Root

Composition Root is a key concept to understand. The Composition Root is where the IoC container must be initialized before everything else starts to use it. Since an application could use several contextualised containers, it could have more composition roots as well. The Composition Root is found in every application that has a main entry point, however Unity doesn’t really have a single entry point that allows objects to be initialized and this is actually quite simply the real cardinal issue of the whole Unity code design. Since it’s of such a significant importance, I will come back to this concept several times in my next articles.

Object Graph

Once objects are used inside other objects, they start to form a graph of dependencies. Let’s say that there is a class A and a class B, then there is a class C that uses A and a class D that uses B and C. D cannot work without B and C, C cannot work without A. This waterfall of dependencies is called Object Graph.

How to use an IoC Container

If, for the moment, we don’t consider objects that must be created dynamically after the start up phase, all the dependencies can be solved right at the begin of the application, within the Composition Root context.

When I started to use IoC containers, my first mistake was to misunderstand its use. I didn’t realise that the container would have taken the responsibility of creating dependency away from me. I just couldn’t imagine a design where I would stop using the new keyword to create dependencies. If we didn’t use an IoC container, this would mean that all the dependencies would be created and initially passed only from the Composition Root. With an IoC container instead, the creation and injection of dependencies works in a different way, as I will soon show to you. If  you haven’t grasped the meaning of this paragraph yet, don’t worry, I will return to this with more examples in my next articles.

Let’s have a look to what a Composition Root looks like using the example that can be found on github:

the container object is not used in any other part of the example, except for Factories. the Factory pattern is a special case and I will explain it later.

What is happening? Inside the SetupContainer method all dependency types are registered into the container. With the method Bind, we are telling to the container that every time a dependency of a known type is found, it must be solved with an instance of the type bound to it. The dependencies are solved lazily (that means only when needed) through the metatag [IoC.Inject].

The application flow starts from this method:

After the MonsterSpawner is built, it will have the dependency IMonsterCounter injected because it has been declared as

and because IMonsterCounter has been previously registered, and bound to a valid implementation (MonsterCountHolder), inside the container. On its turn if the MonsterCounterHolder class has some other dependencies, they would be injected as well and so on…

In a complicated project scenario, this system will eventually give the impression that the [Inject] metatag becomes a sort of magic keyword able to solve automatically our dependencies. Of course there is nothing magic and, differently than Singleton containers, our dependencies will be correctly injected ONLY if they are part of the Object Graph.

Compared to the use of a Singleton, an IoC container gives the same flexibility, but without risking to wildly use static classes everywhere. Dependencies will be correctly injected only if the object that use them is part of the Object Graph. Dependencies can be also injected through interfaces, which allows in future to change implementations without changing the code that uses them. In fact it would be enough to swap the MonsterCounterHolder with another type that implements IMonsterCounter to have new behaviours without changing code in all the places where the dependencies are used.

In reality you can perform more fancy tasks with an IoC container, for example through the use of the concept of providers introduced by my library, but this is not relevant at the moment.

IoC container and the keyword new

It is called Inversion Of Control because the flow of the objects creation is inverted. The control of the creation is not anymore on the user, but on the framework that creates and injects objects for us. The most powerful benefit behind this concept is that the code will not depend on the implementation of the classes anymore, but always on their abstractions (if interfaces are used). Relying on the abstraction of the classes gives many benefits that can be fully appreciated when practices like refactoring and unit testing are regularly used. all that said, one could ask: if I should not use new, how is it possible to create objects dynamically, while the application runs, like for example spawning objects in the game world? As we have seen, the answer is to use Factories. Factories, in my design, can use the container to inject dependencies in to the object that they create. Factories will be also injected as dependencies, so they can be easily used whenever are needed:

Remembering that factories are the only classes that can use the Container outside the Composition Root, the IBulletFactory Create function would look like:

In this way the Bullets will not just be created, but all their dependencies regularly injected, in run-time.

If you wonder why your classes should not be able to create objects on their own, remember that this is not over engineering, this is separation of concerns. Creating bullets and handle them are two different responsibilities.  The Interface Segregation Principle (part of the SOLID principles) is one of the most important design rule to follow in order keep your classes small and simple.

IoC container and Unity

The use of an IoC container, similar to the one I am showing in this article, will help to shift the coding paradigm from an intensive use of Monobehaviour to the use of normal classes that implement interfaces.

A MonoBehaviour, in its pure form, is a useful tool and its use must be encouraged when appropriate. Still our Monobehaviours may need dependencies that must be injected. If the MonoBehaviours are created dynamically through a factory, as it should happen most of the times, then the dependencies are solved through the Object Graph. On the other hand, if MonoBehaviours are created implicitly by Unity, their dependencies cannot be solved within the Composition Root because of the nature of the Unity Framework. Moreover, thanks to the Composition Root, we don’t need to use Monobehaviours to implement managers and other classes that do not naturally belong to a GameObject.

Although in my example the turrets are not created dynamically, their dependencies are automatically solved by the framework during the Awake time and before any Start function is called. As you will see from the code, all and only the Monobehaviours children of the UnityContext MonoBehaviour, will have their dependencies automatically injected.

IoC Container and MVP

IoC container becomes also very useful when patterns like the Model-View-Presenter are used.  Explaining the importance of using patterns like MVP is not part of the scope of this article, so maybe I will write about it in future. However you must know that MVP is great to separate the Logic from the View and therefore allowing to create simpler and focused Monobehaviour. A Monobehaviour would just handle the visual aspect of the entity, while a Presenter can handle the logic. This would look more or less like this:

I found the MVP pattern very useful to design GUI widgets code and in future I actually would love to write a dedicated MVP/GUI framework. MVP didn’t seem to work very well for other entities instead, that’s why I started to look for other solutions as you will see in the next articles.

IoC Container and hierarchical containers

A proper IoC container library should support hierarchical containers, without this fundamental feature, using an IoC library intensively can degenerate in spaghetti code as I will explain later in my next articles. It’s bad practice to just bind every possible dependency in a single container, as this won’t promote separation of concerns. Simply, some dependencies make sense only in given context and not application wise. For example, if we create dependencies for an MVP based GUI, these dependencies could make sense only for this GUI. This would mean that in order to create the GUI, we should use a specialized composition root (which could be defined in a factory). Hierarchical containers are powerful because, while they encapsulate the dependencies needed to a specific context, they will also inherit dependencies from parent containers.

IoC Container and Unit Tests

Often the IoC container concept is associated with Unit Tests. However there is not any direct link between the two practices. In fact, often, Unit Tests frameworks do not use IoC containers at all. Albeit using IoC container will help writing Unit Test friendly classes.
Unit tests must test ONLY the code of the testing class and NEVER its dependencies. An IoC container will make very simple to inject harmless mockups of dependencies that cannot ever break or affect the functionality of the code to test. This can happen thanks to the use of interfaces and the mockup is just one different (often empty) implementation used for the scope of the tests only.


before to conclude, I want to quote two answers I found on StackOverflow that could help to solve some other doubts:


The important thing to realize here is that you can (and should) write your code in a DI-friendly, but container-agnostic manner.

This means that you should always push the composition of dependencies to a point where you can’t possibly defer it any longer. This is called the Composition Root and is often placed in near the application’s entry point.

If you design your application in this way, your choice of DI Container (or no DI Container) revolves around a single place in your application, and you can quickly change strategy.

You can choose to use Poor Man’s DI if you only have a few dependencies, or you can choose to use a full-blown DI Container. Used in this fashion, you will have no dependency on any particular DI Container, so the choice becomes less crucial in terms of maintainability.

A DI Container helps you manage complextity, including object lifetime. Used like described here, it doesn’t do anything you couldn’t write in hand, but it does it better and more succinctly. As such, my threshold for when to start using a DI Container would be pretty low.

I would start using a DI Container once I get past a few dependencies. Most of them are pretty easy to get started with anyway.

and from

Pure encapsulation is an ideal that can never be achieved. If all dependencies were hidden then you wouldn’t have the need for DI at all. Think about it this way, if you truly have private values that can be internalized within the object, say for instance the integer value of the speed of a car object, then you have no external dependency and no need to invert or inject that dependency. These sorts of internal state values that are operated on purely by private functions are what you want to encapsulate always.

But if you’re building a car that wants a certain kind of engine object then you have an external dependency. You can either instantiate that engine — for instance new GMOverHeadCamEngine() — internally within the car object’s constructor, preserving encapsulation but creating a much more insidious coupling to a concrete class GMOverHeadCamEngine, or you can inject it, allowing your Car object to operate agnostically (and much more robustly) on for example an interface IEngine without the concrete dependency. Whether you use an IOC container or simple DI to achieve this is not the point — the point is that you’ve got a Car that can use many kinds of engines without being coupled to any of them, thus making your codebase more flexible and less prone to side effects.

DI is not a violation of encapsulation, it is a way of minimizing the coupling when encapsulation is necessarily broken as a matter of course within virtually every OOP project. Injecting a dependency into an interface externally minimizes coupling side effects and allows your classes to remain agnostic about implementation.

The Example

The framework and the example can be found on GitHub at: You are very welcome to modify it and share your improvements to other users.

Note: you can add more turrets, if you want, using the Editor; thanks to the IoC everything will work without touching code.

Final Notes

I wrote more articles on the subject to investigate further the concept of Inversion of Control. If you are interested, read my new articles starting about the Truth behind Inversion of Control

I strongly suggest to read all my articles on the topic:

43 thoughts on “Inversion of Control with Unity3D – part 2

  1. Thanks for the article, I have been thinking about how to apply DI to Unity as well. Looking forward to more in the series.

  2. Hi and thank you for the comment. I am not planning to write other articles on the topic (I have so many other things I want to talk about), however if you have some other feedbacks or something else you want to discuss, let me know.

    1. Since you mentioned you’re done with this topic, and if we had “something else to discuss”, I would vote for an article about using Entity Systems in Unity.

  3. Hey, very nice articles, that’s exactly what I was looking for, since I come from Flash, huge social games, and I always used Robotlegs or Parsley. Switching to Unity was good but at the same time frustrating to see how “primitive” the software architecture of most of the games out there are.

    What is you opinion about this IoC framework?

    I came across this framework from the post on this blog:

    I’d like to hear your thoughts on that, you can send me an e-mail if possible, thanks a lot!

    1. Ninject is cool (I have talked about it in the article), but it does not work in Unity out of the box. The guy from the article you linked managed to port it, but the problem for me is that the code behind it is too complicated and I wanted to keep it simple!

      1. I tried downloading you project from Github and running in Unity 4, but when I open the scene “Testharness” and run it, I get the error message “The referenced script on this Behaviour is missing!”

        How are you running it? Unity 3.5? MonoDevelop built-in or 3.0?


        1. Ah, I never tried it on Unity 4.0, I’ll do it as soon as I can. I have the suspect that something went wrong with the meta files (maybe the are incompatible) and so you lost all the links. I will check it asap!

  4. Hey. I was very interested in this but I get the same error as Rafael.“The referenced script on this Behaviour is missing!”

    I use Unity 3.5. As I understand it, I don’t see any scripts in the unitypackage what so ever. Isn’t that the real issue?

    Would be really cool to see your example!
    Kind regardsm,

  5. Hey, I began using your framework, and it’s been making my life much easier. But I’m having problems when I load a new Scene. The “game context” where I setup the container and make all bindings is on the “MainScene”, and it gets destroyed when I switch to another scene. Even using DontDestroyOnLoad doesn’t help.

    How do you setup your project if you need to load/unload scenes? Thank you!

    1. Good question. I honestly do not like the idea to keep the container alive through the levels, it can easily create memory leaks. In our (big) project the idea is pretty simple, the container is setup in one .cs file that is linked to one gameobject present in each level. That means that we actually want the container to be destroyed and recreated everytime. This is ok for us, because our data is not meant to be permanent among the levels, is this a problem for you? Let’s discuss it, it is possible that I did not think through it.

      1. I’m working at Wooga with social/mobile games, and from experience it’s fundamental that we have access to the container at anytime, we usually have persistent information across levels. And regarding memory leak, I think it will not be a problem, since there is only “models” and “controllers” stored in the container, low memory usage.

        All the heavy “view” related stuff that really consumes memory (like textures, sprite-sheets, etc) can be destroyed whenever you load/unload scenes.

        I managed to make it work now, I just made the container a static class. In every scene I have a MonoBehaviour object called “GameInit” that will initialize the container, make all the bindings, etc. If it has been already initialized, I skip it.

        This way I can test the game from anywhere, and when I test from the main menu, the other scenes will not initialize twice.

        Anyway, I’m still only prototyping a game, so for “production code” I might change it. Hope that helps! And looking forward to more stuff from you.

        1. Thanks for the feedback. Using the container as a static class defeats the purpose of the inversion of control container design itself, because it practically becomes a service locator.
          This is what I suggest you to do:

          Assuming that you do not have much data to be persistent and this data is unique (like the user inventory, energy and stuff like that), use a class like this to bind in the container:

          class UserInventoryController
          static UserInventoryModel userInventoryModel;

          your container is not static, your UserInventoryController is not static and can be injected, but the data inside is static and permanent. Your problem should be solved in this way.

          1. Sorry, I made the GameContext static, not the Container. Here is the code I’m using for the context:

            using IoC;
            using UnityEngine;

            internal class AppRoot : IContextRoot
            public IContainer container { get; private set; }

            public void Setup()
            container = new IoC.UnityContainer();

            static public class StaticGameContext
            public static bool GameAlreadyInitialized;
            private static AppRoot _applicationRoot;

            static public void Init()
            if (GameAlreadyInitialized)
            D.error(“Game Context Already Initialized!”);

            _applicationRoot = new AppRoot();
            GameAlreadyInitialized = true;

            static public void InjectMonoBehaviour(MonoBehaviour script)
            DesignByContract.Check.Require(_applicationRoot != null && _applicationRoot.container != null,
            “Container not initialized correctly, possible script execution order problem”);


            And I changed the MonoInjection.cs to this:

            using UnityEngine;

            public static class MonoInjection
            public static void Inject(this MonoBehaviour script)

  6. Good Article,
    Now I know why you write your own IOC,

    I’m trying to learn to write better code as mine is what’s the word rubbish, so may give your IOC a test drive. Still trying to get my head around Agile and Solid principles so its nice to have come across your articles.

    I’m also looking to use BDD which i’m thinking may be a good fit for games have you tried user stories with Unity3d

  7. Hi, i am starting my project to the faculty and i got interested in your work. Did you try to use framework? Is it possible to use XML to initilize objects.
    I am interested to in the features of permanent data thought scenes too.

    1. Hello, thanks for your comment. Most of the c# IoC libraries do not work in Unity3D. I know about the XML feature, but it was not something important for me to implement. However the code is opensource, maybe someone could improve it in future 🙂

  8. Hi! I managed to use your framework in my project in a simple and fairly intuitive maner. I just could not put the container persistent through the levels. This feature interested me a lot since i am initializing a set of objects and configuration managers through XML and i wished they were available throughout the various levels. Maybe the problem is in the design of my application due to my lack of experience.
    My initial approach used a singleton that persisted through various levels, but your solution is much more cleaver and clean however the solution using static attributes does not work due to the state of the objects. Although it seems unreasonable, what do you think about transform the container in a singleton to ensure the persistence?
    About the use of XML in IoC, I have not had time to properly analyze your framework and I have yet to get used to the concepts of IoC, do you think that a new implementation of the provider using XmlSerializermaner would do the trick?

    1. Hi,

      Transforming the container in to a singleton hides a big risk of memory leaking. This is the only thing you need to be aware of.
      I did not think about a way to use an xml configurator, but I bet it would be easy enough to implement (using reflection).

  9. Hi, great articles, I was looking for DI framework for Unity, plus some theory in IoC, for a while now and this seems like exactly what I wanted.
    My concern is about performance of the code, as I and our team are pure game developers, we are always worried about it, so we try not to rely on interfaces or getters/setters and use more “accesible” code like public variables or static classes, etc.
    So you can imagine that trying to introduce a new paradigm like this in a team not used to these techniques can be very difficult.
    What are your thoughts and experience in this matters, performance of the code using DI on a full production project, and evangelization of a new paradigm in a team?.
    Thank you.

    1. Hello and thanks for the comment.
      Most of the injections happen during the initialization phase so performance should not be an issue. However it is true that injection could happen anytime using factories as well.
      Since my IoC relies on reflection and I did not write any caching method to speed up the injection of known types, I would not use IoC factories to create/inject objects while the game runs, unless it happens sporadically.

  10. Hi, Sebastiano!

    I tried to use your DI container, but looks like I miss something …
    In this sample I am trying to create two different objects:

    public class SimpleClass
    public Guid _id = Guid.NewGuid();

    public void TestBuild()
    var container = new UnityContainer();


    var obj1 = container.Build();
    var obj2 = container.Build();
    Assert.AreNotEqual(obj1._id, obj2._id);

    The test fails. So, all objects build by container are singletones?
    Could you please explain me this behaviour?
    Thank you in advance

    1. Sorry, looks like all signs ‘greater’ and ‘less’ were eaten by blog engine.
      In my test I am trying to create two SimpleClass objects one by one.
      container.Build() returns the same instance twice

      1. Thanks for the comment, this is indeed the intended behavior…that’s why it is called AsSingle! (btw they are not singletons, they are just the same instance)

        if you want different instance of the same class, you should use factories…let me know if you need an example.

        1. Hi, Sebastiano

          Thank your article, i am studies this framework and try to using in my project, now.
          I hope to know how to use factories in your container, is it like your MonsterFactory in the example, or have other method to do?
          If there has another method, can you give me the example?

  11. Hi Sebastiano,

    I just started coding with Unity3D (only about a week in), but it only took me a couple days to realize that I needed a DI container of some sort. So I’m very happy to have found your project! This looks like a big step in the right direction.

    I haven’t used Ninject before, but I have used Castle Windsor extensively with my business development MVVM / MVC style projects. So I do know how complex it can be considering that these containers not only handle instantiating objects, but that they also manage the “lifetime” of the objects and handling disposal in many cases (unless specifically instructed not to, as in when a dependency is registered as a Transient in Castle Windsor).

    Can you elaborate on why you think Ninject is overly complicated for use with Unity / game development? Is it just that you just want the container to simply instantiate and inject the objects, but you do not want the container to try to manage their lifetimes? This way, you are responsible for destryoying all created objects?


    1. Hello Jordan, thanks for the feedback. Since you are new to Unity I have to highlight that the real reason why I needed an IoC container is the lack of a proper way to inject dependencies inside monobehaviour objects in Unity. Of course, with the introduction of a composition root, I am also able to avoid to use monobehaviour objects when they are not needed.

      The original version of Ninject does not work in Unity, Uninject should, but when it came out my version was already enough. Point is that I am working on a relatively big project and I do not need nothing more, while Ninject is quite a huge project. Never understood why an IoC should be so complicated. My IoC lacks some features, but I never needed more (I am working on a new version, which is better, but not much different).

      I do not know exactly what you mean with the management of the lifetime, I do not know ninject so well anyway. In everycase once a dependency is injected, a new reference is obviously created, so the IoC framework cannot really do much about it.

      In my simple framework, the objects are alive as long as the container is alive (and of course other objects reference to them). Remember c# uses garbage collection.

      Can you tell me some features from ninject that you really find useful? So far the only one I am really missing is the injection by constructor. Another interesting feature could be to use hierarchical containers, but I never had the need for it so far.

  12. Well I have 1 feature idea, don’t know if it is already available in your IoC container or in Ninject but may be usefull:

    When a container is destroyed it may print a log of wich dependencies are not used. If codebase is wellwritten and everything is concern separated, it is likely that after some refactoring (maybe removing a dependency) the log shows that some classes were not used.

  13. Hi my name is Antonio Zamora and I’m very interested in game programming patterns. I would really like to share my thoughts with you (I’m not an native speaker so please excuse my english).

    As you I have worked with robotlegs before and I praised the philosophy it had. I loved actionscript and I felt very good working with the adobe platform. But later adobe seemed to take some bad decisions that I didnt share so I searched for a new place to look at.

    I discovered unity and I liked the whole idea of gameobjects. As you mention the gameobject can have a view or not. This remembered me the while idea of mediators and actors from robotlegs so as you I decide to follow some simple rules.

    One of them was, as yoo mentioned, forget about the use of gameObject.Find() Since then I’ve tried to understand well the whole model. I decided that for each prefab I have to had a Mediator, so you get to see something like this:

    With this I try to follow your rule number 2 “MonoBehaviours are reusable, single responsibility classes.”

    So far I have been really happy, because my designers only have to pay attention to the mediator on each prefab, be it to tweek an speed or to increase a variable that is exposed.

    I have been always interested in this approach of programming but sometimes this mediators keep growing and growing. I try my best to extend its functionality by adding components but well, sometimes the work have to be done.

    Finally one last question, how do you approach your number 5 rule:”The behaviour of a GameObject should be extended adding MonoBehaviours instead of adding methods to a single MonoBehaviour.”

    What do you do normally when you are implementing you monobehaviours, do you do a lot and a lot of components? or do you tend to keep the gameobjects as clean as components as posible?

    Thanks for the post.

    1. the idea is to create as simple as possible monobehaviours and add as many as you need. So let them do just one thing, if you need 10 different things, use 10 different components on the same GameObject.

      For the MVC (or better MVVM) pattern is a little bit more complicated due to the Unity limitations, but it is still doable. My idea is that the Monobehaviour becomes the view or the model, sometimes both and a presenter is injected in to it. The view redirects the events (awake, start, update, oncollision, onmousedown etc..) to the presenter (controller or viewmodel) which decides what to do.

  14. Great article! Thanks for your work. Unity 3D has many specific features and you offered amazing ideas and tools for resolve it. I used a Singleton approach before (DI ideas) as a start as a single way to manage objects but for complex projects such way is fall down road. Also, you are right concerning MonoBehavior using without any appropriate foundation.
    Unity 3D Platform Lead at XIM Wireless

Leave a Reply