IoC Container for Unity3D – part 2

In my previous article, I briefly introduced the problems related to injecting dependencies using 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.

Before to discuss the example I built on purpose to show the features of the framework, I want to share my experience with the 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 are) extensively used to ease our work. That’s why, when I shifted from traditional procedural C++ programming to event based actionscript coding, I started to use Robotlegs. Robotlegs is an actionscript IoC Container.

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 through setter and getters was a better practice. However after some time, when I moved to C#, I started to experiment with Ninject and discuss the practices with its author. As result of these discussions 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 understand the concepts first:

Composition Root

Composition Root is a fundamental 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.

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.

At this point we are ready to use an IoC container.

How to use an IoC Container

As long as the objects do not need to be created after the application has been initialised, 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 inject the container inside the objects to fill their dependencies that I used to create explicitly using the new keyword. The rule instead is that the container should be explicitly used only in the Composition Root. Exceptions, most of the time, mean that there is something wrong with the design.

In our example the Composition Root looks like this:

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 we are registering all dependency types into the container. With the method Bind, we are telling to the container that every time a dependency of a recognised 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, inside the container. In this specific case is simple to understand how the MonsterSpawner dependencies have been explicitly injected by the container. The container is not used anywhere else except for the GameObject factory where it’s needed to fill the dependencies of the entity dynamically created, hence other dependencies are injected solely thanks to the Object Graph links. If MonsterCounterHolder had some dependencies, they would have been injected as well and so on…

In a complicated project scenario, this system eventually will give the impression that the [IoC.Inject] metatag becomes a sort of magic keyword that will solve all 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.

The Object Graph itself is the main difference between the use of an IoC container and a Singleton container. The dependencies are not scattered without any constriction among the classes, but they must follow the Object Graph flow.

If, using Singletons and Singleton containers, your code starts to feel like a Jenga game, then it is probably the time to start to look at the Inversion Of Control solution.

IoC container and the keyword new

It is called Inversion Of Control because the flow of the objects creation is inverted. The control 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 heavily 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 the object that they create.

your class could have something like:

where the IBulletFactory implementation is allowed to inject the dependencies inside the newly created Bullet instance just using directly the Inject function of the container. Looking like:

Beside, if you wonder why your classes should not be able to create objects on its own, remember that this is not over engineering, this is separation of concerns.

Creating bullets and handle them are two different responsibilities and respecting the Interface Segregation Principle (part of the SOLID principles) is one of the most important design rule to follow in order to not have humongous and cluttered classes.

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 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.

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. There is one condition though, the GameObject must be in a hierarchy where the root is a GameObject that holds a UnityContext MonoBehaviour (as showed in the example on github).

IoC Container and MVP

IoC container becomes also very useful when patterns like Model, View, Presenter are used. Theoretically the triad should not be known outside the triad itself, since the way to communicate outside is through services or commands injected. 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, it is interesting to highlight how I uncouple the data that I want to be edited through the Unity Editor and the logic that must use this data. Usually happens that, just because we want to let the designer edit some public variables, we create a MonoBehaviour without any further reason. This would break my rules about the use of MonoBehaviours. Unluckily in this case a compromise is needed. The best solution I found so far is the following:

While you can change the way I exploited the idea in several ways, the main concept is that the MonoBehaviour is totally uncoupled from the logic (pathController) and it could even be destroyed since it is not needed for our purposes anymore. If PathController was a Presenter, pathData could have been the Model.

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 create dumb mockups to inject valid dependencies that cannot ever break or affect the tests of the main class itself. This can happen thanks to the use of interfaces, where the mockups become just one different (often empty) implementations 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

41 thoughts on “IoC Container for 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