Tag: dependencies

Stitching – Combining Unity3D And Autofac

Stitching - Combining Unity3D And Autofac

Before We Talk About Stitching…

In Unity3D, the scripts we write and attach to GameObjects inherit from a base class called MonoBehaviour (and yes, that says Behaviour with a U in it, not the American spelling like Behavior… Just a heads up). MonoBehaviour instances can be attached to GameObjects in code by calling the AddComponent method, which takes a type parameter or type argument, and returns the new instance of the attached MonoBehaviour that it creates.

This API usage means that:

  • We cannot attach existing instances of a MonoBehaviour to a GameObject
  • Unity3D takes care of instantiating MonoBehaviours for us (thanks Unity!)
  • … We can’t pass parameters into the constructor of a MonoBehaviour because Unity3D only handles parameterless constructors (boo Unity!)

So what’s the problem with that? It kind of goes against some design patterns I’m a big fan of, where you pass your object’s dependencies in via the constructor. You can read my little primer about constructor parameter passing, dependency injection, and Autofac to learn more.

The challenge I’m trying to address is that my non-MonoBehaviour classes are all going to be setup to use constructor parameter passing as much as possible but the MonoBehaviour classes cannot. So I’d like to reduce the amount of disjoint coding styles as much as I can and make the MonoBehaviour classes feel like the rest of my stuff!

What Is “Stitching”?

Here’s where this little pattern I created called “Stitching” comes into play. Stitching involves using a class referred to as a Stitcher that’s single purpose is to take parameters in via a constructor, and wire them up to either public properties or public fields (but I REALLY suggest using properties) on the MonoBehaviour that we instantiate through the GameObject.AddComponent() API.

The code ends up looking something like this:

public sealed class MyComponentStitcher
  private readonly IDependency _dependency;

  public MyComponentStitcher(IDependency dependency)
    // take in our dependencies and save them as fields
    _dependency = dependency;

  public MyComponent Stitch(GameObject gameObject)
    // create the MonoBehaviour instance using the Unity3D API
    var componentInstance = gameObject.AddComponent<MyComponent>();

    // wire up our dependencies (assign our field to a property on the component)
    componentInstance.Dependency = _dependency;

    return componentInstance;

Where you can see that:

  • We inject dependencies into the Stitcher’s constructor
  • We call AddComponent() with the component type we want on the object we want to “stitch” to
  • We mutate the component
  • We return the newly made component

How Do We Use Stitching In Practice?

Now that we see the pattern for a how a Stitcher works, how do we actually use Stitching in practice? Let’s start by using another example:

public sealed class SomeClass
  private readonly IMyComponentStitcher _stitcher;

  public SomeClass(IMyComponentStitcher stitcher)
    _stitcher = stitcher;

  public void MyMethod()
    // create a new Unity3D game object
    var gameObject = new GameObject("My Game Object");

    // "stitch" our 
    var myComponent = _stitcher.Stitch(gameObject);

    // we can use some information that would have been injected into the constructor
    // this should print the injected value

From this, you can see that:

  • We have a class called MyClass following our constructor parameter passing paradigm
  • The method MyMethod()
    • Creates a new game object
    • Adds a MyComponent instance to our game object by calling the Stitch() method
    • Using our imagination and the example above, pretend our Stitcher implementation takes a parameter in its constructor to assign to the InjectedInfo property of of MonoBehaviour
  • Logs out the value of the InjectedInfo property found on our newly created instance

So What Makes Stitching Better?

You might feel like this is extra code right now, but this is where the power of Autofac comes into play. You can read my article about using Autofac with Unity3D for more information.

By creating a Stitcher, we can register it to our Autofac container. The Autofac container will then resolve any dependencies that our Stitcher requires for us. The net effect of this is that when we Stitch MonoBehaviours to GameObjects, we get what feels like Autofac resolving dependencies for our MonoBeaviours. We don’t need to mutate MonoBehaviour fields/properties all over our code to assign the dependencies the script needs to use. Instead, we treat the Stitcher class like a factory for our MonoBehaviour.

So in summary:

  • Stitching allows us to leverage Autofac for instantiating MonoBehaviours
  • Stitcher classes essentially become a factory class for our MonoBehaviours (with the side effect that they *must* mutate the GameObject that we need to attach the MonoBehaviour to)
  • Allows assignment of MonoBehaviour fields/properties for initialization to exist in one spot so we can put the bad object mutating code in one spot that feels hidden

Using Autofac With Unity3D

Autofac With Unity

Why Consider Using Autofac With Unity3D?

I think using a dependency injection framework is really valuable when you’re building a complex application, and in my opinion, a game built in Unity is a great example of this. Using Autofac with Unity3D doesn’t need to be a special case. I wrote a primer for using Autofac, and in it I discuss reasons why it’s valuable and some of the reasons you’d consider switching to using a dependency container framework. Now it doesn’t need to be Autofac, but I love the API and the usability, so that’s my weapon of choice.

Building a game can result in many complex systems working together. Not only that, if you intend to build many games it’s a great opportunity to refactor code into different libraries for re-usability. If we’re practicing writing good code using constructor dependency passing with interfaces, then things really start to line up in favour of using a dependency injection framework.

Getting Set Up

At the end of my autofac primer article, I provided a link to the Nuget package for Autofac. You’ll notice that there’s a version dependency for .NET 4.5, so if you’re not sure how to get Unity3D working with .NET 4.5, you’ll want to check this other article of mine. It’s very simple, so don’t worry!

Unity3D, at the time of writing this and using version 2018.1.1f1, there’s no native Nuget package support. I haven’t spent too much time investigating alternatives, but not to worry. I’ll explain a quick work around. The TL;DR is that we need the binaries from the Nuget package to be loaded up by Unity3D and we’ll miss out on the Nuget-y-ness for now. Not a huge deal since we’ll still have Autofac support!

  • Start a new Visual Studio C# project
    • Ensure that the .NET framework is at least 4.5 and more specifically, the version of .NET that you’d like to use in your Unity3D project
  • Open up the Nuget package manager in Visual Studio
  • Search for Autofac online in the package manager (it should be the same one I referred to above!)
  • Add this package to your visual studio project
  • Compile this visual studio project
  • Assuming you built in debug, go to the output folder (which is in bindebug if you didn’t change anything from default)
  • In the output folder, you’ll find “Autofac.dll”
  • You’ll want to add this into your Unity3D project’s “Assets” folder
    • I like nice folder hierarchies, so I’d suggest making a subfolder inside of “Assets” called “Third Party” or “Dependencies”… Something that’s obvious for what it means
    • Drop in the Autofac.dll file into there
  • Unity3D will add a corresponding *.meta file to go along with this

Great! We’re almost there. If you want to test it out, open up a script from Unity3D. This will launch a new Visual Studio instance if you haven’t opened up one for your Unity project yet. At the very top of your file you should be able to type:

using Autofac;

And the namespace should resolve! If not, sometimes this takes Unity3D a refresh operation to regenerate the project file on disc, so if you switch to Unity3D again and it starts doing some processing, switching back to Visual Studio might resolve this.

Using Autofac With Unity3D

Up until this point, we’ve proven we can reference Autofac. I’m not going to explain all the ins and outs for how you’ll want to organize your Autofac initialization in this post, but we can walk through a quick example!

  • Pick a game object on your scene
  • Add a new C# script to it
    • Call it whatever you’d like, but make sure you know how to open it
  • … now go open it in Visual Studio 🙂
  • We should have a method in there called Start()
    • If not, feel free to add it:
    • private void Start()
        // TODO: we'll add stuff here
  • Let’s use this code to make a new class that you can put inside the same script file for now:
    • public sealed class MyAutofacObject
        public MyAutofacObject()
          Debug.Log("Constructor for our object!");
        public void DoThing()
  • Inside this start method, let’s try doing something VERY simple to prove Autofac works!
    • var containerBuilder = new Autofac.ContainerBuilder();
      var container = containerBuilder.Build()
      var instance = container.Resolve<MyAutofacObject>();

Now if we run our game, here’s what should happen:

  • The script attached to the game object should run
  • The Start() method on the script should be the first thing that goes
  • The code we added should:
    • Make a new ContainerBuilder
    • Register our MyAutofacObject type as a single instance
    • Build the container
    • Resolve an instance of our type
    • Log out a message saying it’s in the constructor
    • Log out a message that says Test!

And voila! It’s simple, but it should demonstrate that Autofac is working!

Next Steps

This is a very contrived example of using Autofac with Unity3D. It proves that the code can be run, but it doesn’t do too much that’s useful. There are going to be many considerations you’ll need to make for how you want to organize your dependencies, register your classes/interfaces, and so on.

I’ll continue to add into this Unity3D series of posts, but let me know what else you’d like to know about using Autofac with Unity3D! I’d be happy to try and answer, or even create an article to help explain.


Dependency Injection with Autofac – A Primer

Autofac Logo

Before Autofac…

I’ve written before about IoC and dependency injection, but these are older posts and my perspective and experience with these topics has fortunately been growing. I think they’re incredibly important when you’re building complex systems, but the concepts can offer some benefits in all of your programming! When you get in the habit of practicing this kind of thing, you can get some pretty flexible code… for free.

So a quick recap on what I mean by dependency injection here… I’m mostly focused on passing interfaces into constructors (and yes, I’m going to be using C# terminology as I do in most of my programming examples, but these concepts are generally the same in other languages). The benefits here:

  • You can write implementations that don’t depend on other implementations… Just an API.
  • Not depending on an interface means you can write mockable code for your unit tests. (I’ll follow up with a post on this to help provide examples)
  • You can swap out functionality by providing a different implementation of an interface and NOT re-writing core code
    • This can be a very powerful refactoring tool
    • This can allow creation of new functionality in a system simply by adding one small class instead of re-writing code

So that’s all good and well… So what do we use Autofac for?

When you might want to take the leap to Autofac

So you’ve been writing code now using interfaces in your constructor parameters. You’ve got nice modular code using composition. You have unit tests. Things are great.

There comes a point where you decide you need to break open a class in the depths of your system and provide it a new interface as part of the constructor. This is in line with the constructor parameter passing paradigm (nice alliteration, woo!) you’ve been using, so it feels good. You modify your constructor to take the new interface parameter. You change up your method to call this new interface’s API. You update your tests. It works!

Now you need to make the rest of your application work though, and it turns out because this class is created so deep down in your system, you need to find a way to pass this new interface implementation allllllllll the way down. And suddenly, you find you need to break open 10 other classes to pass this interface into the constructor. It’s a simple change in that it’s the same change in 10 spots… But it’s 10 spots. And it’s tedious. And you got lucky because you own this code and you don’t need to worry about breaking the constructor API for other people.

But it might be time to look into something like Autofac at this point because it can make this problem disappear for you.

Enter Autofac!

Autofac is awesome. The end.

But seriously, Autofac is one example of a dependency container framework. The idea with a framework like this is that programmers can register things to the container and then at a later point these things can be resolved. So you could:

  • Decide to take a particular implementation and register it so that it can be resolved by its interface
  • Decide if you want a registration to act like a singleton (and remember, a singleton does NOT have to have global access… it just means literally a single instance)
  • Run callbacks when an instance is created
  • … and so much more

In my opinion, the two major benefits of Autofac as they relate to this example are:

  • You can better organize the top level of your application to wire up specific implementations to use in your code
  • … Autofac can magically resolve the dependencies for you so it solves that nasty problem of passing down dependencies via constructors to deep areas of your code

You’ll need to be careful that you don’t abuse the container though! It’s considered an anti-pattern to use the container to manually resolve dependencies across various areas of your application (generally this is referred to as the Service Locator (anti)Pattern, but people go back and forth on why it’s good or bad). The “proper” use case is to resolve your single entry point class in one spot, call the methods you need on your entry point class, and let Autofac do its magic to resolve all of your registered dependencies.

Where Can I Get Autofac?

This is the easy part! You can use your Nuget package manager in Visual Studio to find the right package for your .NET framework dependency. Check it out at the Nuget Gallery!

What’s Next?

I have some examples I’d like to write about next for using Autofac including:

  • Using Modules for Organizing Code Dependencies
  • Patterns for Dynamically Resolving Modules Across Assemblies
  • How to use Autofac with Unity3D

But I’d love to hear what you want to know more about! Comment and let me know, and I’ll see what I can do.

Singletons: Why Are They “Bad”?


The very first thing I want to say is that I don’t think singletons are inherently bad–even if it means I am cast away from the rest of the programming world. There’s a time and a place for the singleton. It’s really common for people to get caught up with their perspective on something that they outright refuse to acknowledge the other side of it. I’d also like to point out that if you have a strong opinion on something and you find that other people also have a strongly opposing opinion on the same thing, there’s probably good take away points from either side. In this post though, I’m going to focus on why singletons are “bad”, because for me it means acknowledging one of the two main perspectives–that they are the best thing since cat videos met The Internet or they are the worst thing since Justin Bieber.

Let’s clarify what a singleton is here so we’re all on the same page. Maybe you’re under the impression it’s something slightly different than what I’m about to be talking about, so I’d rather make it clear from the beginning. And for what it’s worth, if this isn’t the exact meaning as set in stone by the singleton gods, then that’s sort of unfortunate… because this is going to be what I’m discussing.  From Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four, a singleton must:

Ensure a class has only one instance and provide a global point of access to it.

So, with that incredibly complex definition, let’s get into it.


Global Dependencies

There’s approximately 3.2 billion articles on The Internet that will tell you that global variables are the enemy. I mean, I could do some of the work for you, but you could check out this, or this, or this… There’s still billions more. Usually when we have ~99% of people agreeing on something, they probably have a pretty good point, right? You’ll notice after a bit of searching that one *big* problem with singletons is the fact that they are just a different way to dress a global variable. Thus, all of the arguments for why global variables are bad could be used against singletons.

There are a few (quite a few) major problems with having global dependencies:

  • You’ll be putting yourself at risk for dealing with deadlocks if you need to lock your resources
  • Your singleton can become the resource bottleneck in your application
  • It’s hard to know who you’ll affect by modifying the global variable
  • Testing becomes difficult because the tests may depend on the state of the singleton
  • Dependencies aren’t obvious from examining the API

Quite simply, global dependencies can be pretty scary. If you and you’re team are experienced enough, trying to weave in some new features or heavily modify code relying on singletons may not be that challenging for you. Maybe. But testing can get super messy.

When you write unit tests, you want to ensure that each test can be run independently of the others. You need complete control over your state. This can be a big problem if you run two tests in a row that depend on state provided by a singleton. Consider the following set of tests that depend on a singleton in a sample run:

  • Test1 increases the count property on a singleton by 1 as part of the side effect of the test.
  • Test2 also increases the count property of the same singleton instance by 1, just as Test1 did. However, Test2 is explicitly testing this property as part of it’s validation to ensure the value transitioned from 0 to 1.

When you run Test1 all by itself, it behaves as you expect. Great! Now you move onto Test2. Simple. You got it working. You’re all excited so you run them all together. Uh oh… The tests failed! But how? You don’t believe it, so you run them all again. Now they pass! This is a crappy spot to be in. If the test suite executes Test2 before Test1, your tests will work. If the test suite executes them in the opposite order, your tests will fail because the singleton instance will have had its count property increased twice. The global state of the singleton comes back to haunt you.


Tight Coupling

Most experienced developers know that you want to decrease coupling and increase cohesion because this, generally speaking, makes for a good API and extensible code base. Now this point is related to the global dependency points I was previously stating, but it deserves to be addressed on it’s own. The global dependency topic was more of a focus on the application at run time. That is, it becomes difficult to know and manage how your application behaves at run time when you share global state across the entire thing. It’s challenging to to start adding new functionality to your application or modify existing components of your application that depend on the global state because the dependencies just keep growing.

Coupling, in my opinion, is more of an issue with compile time. With singletons, you start to design classes that depend on singletons and thus you are relying on a specific implementation (Maybe you could check out dependency injected singletons?). Singletons, generally speaking, are a single instance of a concrete class. You start to code classes and object hierarchies that are then depending on this concrete class, and this can potentially (and I say potentially, because I would never claim it’s “always”) lead you to a dead end. Let’s consider a scenario:

We’re coding an application that uses a singleton for the data access layer of our application. We have a MySQL data model that we’ve coded as a singleton. We expose a few methods to read and write records to the database using some SQL, and things are great. Then, one day, we speak to our customers like we usually do to ensure we’re meeting their expectations. They inform us that we really need to be able to support a document database like MongoDB in addition to MySQL. Hold on. Wait. You mean our code that uses our data layer needs to be agnostic to the database under the hood?! But… But our singleton is only able to deal with MySQL… (I wrote about how to get yourself out of this situation here, although I would not claim it’s the ideal scenario). If we would have been passing around references to something that met a nice and clean model interface spec, we’d likely be able to hide the implementation details and completely avoid this problem.


Singletons Disrupt The API

Because I like to design complex systems in code, API and architecture is something I like to focus on. There’s an awesome posting over here by Miško Hevery about this very problem. He does a great job describing the problem with examples, so I’ll only try to summarize some of the main take-away points I got from it.

There’s nothing to stop someone from putting some heavy initialization logic in a singleton. I mean, you shouldn’t (because you can’t guarantee when this is going to happen!) but there’s nothing that prevents it. As such, simply calling a constructor on some class (which you might assume to happen pretty quickly) actually ends up taking seconds. Not a couple milliseconds… But seconds. Oh. I guess you didn’t realize your class was trying to call a singleton instance that was connecting over The Internet to some host on the other side of the planet during its initialization. Surprise. Singletons can mask this kind of stuff because it’s not explicit in the API. It kind of goes back to coupling but I wanted to point out that this kind of stuff can get scary.

This can be completely mitigated by incorporating the dependencies right into the API. There’s no hiding crazy database initialization or downloading data from the internet in a constructor (well… it just reduces the likelihood of you doing it so easily I guess). You use interfaces and construct classes in the order that you need them, and this doesn’t end up being some magical process that happens behind a curtain. If one class depends on another, so be it (it’d be nice if it just depended on the interface…), but pass in the reference that you require. Singletons often end up being the shortcut, but what’s easier for you to code now may not be easier for someone to extend upon and understand in the future.



Singletons. You’ve likely seen them. You’ve likely heard bad things about them. You may have even used one yourself. Shame on you. Like all debatable things though, there’s always going to be another side to it. If you take away anything from reading this, I hope it’s that you question what the other perspective is. Fully understanding something requires you to look at all sides.



This article was based on information I obtained from the following sources (as well as my own experiences, of course!):

  • Subscribe to Blog via Email

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress