A Very Strange Xmas…


Note: Ardbeg distillers have never heard of StrangeIoC. Even if they had, it’s doubtful they’d approve this image.

Happy festival of your choice!

This will likely be my last post of 2013, and what a year it’s been! In January I was just beginning to conceive of an IoC framework for Unity3D development. Today we not only have the framework, but a growing community of people interested in what we’re doing. As far as I’m concerned, there’s no better definition of success than that people like the work you do.

This post won’t have any useful technical tips or release information (other than to note that v0.7 won’t be official till early January). I just want to take a moment to thank a few people important people.

First, a huge thank you to my employer, ThirdMotion, Inc., who quite literally footed the bill so you could have cleaner code. They could have insisted I write a simpler IoC framework. It would have been faster. They could have refused to open source it. It’s not easy to build something worthwhile and then give it away for free. It’s also not easy to explain that decision to your investors. And they could also have said “Right. That’s done. Get back to work!” Instead, they’ve generously allowed me some of my working week to keep making the world a Stranger place. You and I owe then a protracted slow clap.

A big shoutout to my lovely wife Orla, who puts up with me working weekends and evenings instead of doing the countless things I should be doing around the house. She’s also probably unwittingly the most knowledgable person on Earth about Strange, given the number of times she’s had to hear me explain it.

Of course many friends and colleagues have had a hand in making Strange what it is. I won’t name you all one by one but y’all know who you are, so know that you have my sincerest gratitude.

One particular colleague does deserves special mention. As much as I appreciate code reviews, consultations, tutorials, blog posts and tweets, one guy has really been out in the trenches with me helping to build a better framework. Will Corwin, author of Signals and the new implicit bindings package, is the best, most enthusiastic coding partner I could ask for. This Ardbeg (which for Will I admit should be a Bowmore) is for him!

Finally, and most importantly, my thanks to you, whoever you are. If you’re reading this it means you’re interested in what we’re doing. You’re interested in writing better code and improving the ecosystem of Unity3D development, hopefully bringing more of your colleagues along for the ride. I evolved as a developer with Actionscript…from spaghetti code to OOP to, ultimately, IoC. It works. It’s better. And Unity will be a better place because of people like yourself.

Have a lovely New Year.

MonoDevelop 4.0.1, OS X, and git

Super-quick post. Some of you will recall that Git support in MonoDevelop 2.x chewed up CPU cycles, slowing the editor (and everything else on your computer) way down. The same is true in MonoDevelop 4.0.1, but the location of the fix has changed.

To disable Git and SVN in MD 4.0.1, you now go to MonoDevelop-Unity > Add-in Manager > Installed Tab > Version Control. Then disable all plugins in that directory. Doing so lowered MD’s CPU usage when idle from 120-140% to near 0%.

Not surprisingly, the method is the same in Xamarin…but I don’t see the massive CPU spikes in Xamarin, even with git and SVN support enabled.

Hope that helps someone!

Pools at last…

Pools at last…Pools at last! THANK GOD ALMIGHTY….OK, I might be overplaying this.

splashI’ve written many times of my desire to add a native pooling capability to Strange, and at last that feature is primed for release as part of v0.7.

To recap the purpose in brief: pooling saves memory, and therefore improves performance, particularly on mobile. This post explains our implementation of pools, and details how to use them. If you’re interested, a prior post goes into  the question of “why?” in more detail.

A pool, as I see it, consists of three parts:

  • Poolable (recyclable) items. That is, items capable of being reused instead of thrown away. While you can pretty much pool anything, we’ve created an IPoolable interface which is useful for establishing the important behaviors of a pooled instance.
  • The pool, which is at heart just a collection of recyclable instances. We have a Pool class, of course.
  • A client. The agency that wants to use the pooled instances, and is responsible for returning them. The client typically thinks in terms of IPool<T>.

That last bullet is important, and differentiates a pool from a simple instance provider. The client of a provider simply takes instances. The pool’s client knows it has to put things back. Don’t forget this point, lest all the virtues of pooling be lost on you.

There are three main uses for pools in Strange. We’ll go through them from the simplest to the most complex.

Use Case 1: Event Pooling

Event pooling is by far the simplest form, especially as you needn’t even know it’s happening. Quite simply, the EventDispatcher now implements a pool, recycling its events instead of throwing them away. Obviously if you use Signals this has no particular impact on your life.

Since Event pooling is happening under-the-hood, you don’t see any of the three parts mentioned above.

Use Case 2: Command Pooling

Commands (whether for Events or for Signals) may now be pooled at your discretion. In general, there is no need to do so, BUT (notice that it’s a very big ‘but’) it can be highly advantageous to do so for Commands that fire a lot, as with Commands fired as part of your main game loop. This was the key reason for implementing pools: it is now possible to mark a Command for pooling, so that Strange will be more friendly for use in game loops!

Marking a Command for pooling is exceedingly simple, and looks like this:


There’s a Signals version, of course. I hope it won’t disappoint if it looks almost exactly the same:


The result of marking the binding this way is that the Command will fire and get recycled when it’s done. A retained Command can also be recycled, but there are a couple important caveats.

First, remember that instances returned to a pool need to be restored to their pristine state for future use. Leaving uncleared references could lead to memory leaks or other problems. Therefore, if you Retain() a pooled Command, make sure you clear any variables in the new Restore() method, the express purpose of which is to clear data immediately before recycling. You don’t need to worry about cleaning up anything injected; these properties will be cleaned up automagically by Strange. And you don’t need to call Restore() yourself as it’s called as a normal part of the Release() cycle.

Second, note that even an empty Command takes some memory, so don’t mark commands Pooled() willy-nilly. Consider whether or not pooling each specific Command gives you an advantage.

Use Case 3: Everything Else

That headline might sound a bit glib, but it pretty much describes the case of you using Pools when you need them. It’s not automated at this level, but pools have been designed to be both simple and powerful, so that you can easily recycle most anything you like.

Here’s a mapping for a typical pool:


Note first that we tell the Pool what the Type of its instances will be. A pool’s instances must all be of the same concrete type.

But there’s something more important to note here: we’re not mapping a pool of type Starship to an interface of, say, IShip. This is profoundly disappointing to me, but it’s a limitation of the version of .Net that Unity uses. While you can map IPool<SomeClass>, you can’t map IPool<ISomeInterface>, or even IPool<SomeSuperClass>. You’ll get an error.

Finally, note that we have to bind the class that the pool provides. This is because the pool by default uses the Injector to instantiate its instances. This is useful, since most of the object creation can be automated in the usual IoC form. But note that if we want we can override this behavior (see below).

To use the pool we just inject it:

public IPool<Starship> shipPool { get; set; }

// used somewhere in your class
Starship shipInstance = shipPool.GetInstance();

// and when you're done with it

So that’s all pretty straightforward, but we’ve added a number of configurable little details that allow you to customize how your pool works.


pool.size = 16;

Your pool’s default size is 0, which is a special case meaning ‘infinite’. A pool with a size of 0 will expand as the need arises, so as long as you return the checked-out instances, all the rest of the management is taken care of for you. (NB: ‘size’ refers to the allowable number of instances. There are other properties — instanceCount, available — for inspecting the current state of the pool.)

If you fix the size, then other behaviors governing overflow will kick in.

Inflation Type

pool.inflationType = PoolInflationType.INCREMENT;

If your pool size is 0 it will inflate when necessary, and you can control the type of inflation with the PoolInflationType constants. Your options are INCREMENT, which will add one more instance to the pool whenever you need one, and DOUBLE (the default), which will double the pool size.

Overflow Behavior

pool.overflowBehavior = PoolOverflowBehavior.IGNORE;

If your pool is set to a fixed size, then overflowing the pool (i.e., asking for more instances than the pool has available) will result in one of the following behaviors, depending on the PoolOverflowBehavior. By default, an overflowing pool with throw a PoolException. If you would rather get a warning or ignore it altogether, got can set this value to WARNING or IGNORE. Both these options result in returning null instead of an instance.

Instance Provider

As noted above, the pool by default goes straight to the Injector in order to instantiate its instances, but this isn’t always desirable. Sometimes you want to control the instance creation just so. You can do this by simply writing your own provider, then setting the instanceProvider property of the pool to your custom implementation. Here’s an example. This provider creates an instance and sets a property before returning it.

class ShipInstanceProvider : IInstanceProvider
     public T GetInstance<T>()
         object instance = GetInstance (typeof (T));
         T retv = (T) instance;
         return retv;

     public object GetInstance(Type key)
         Starship retv = new Starship();
         retv.phasers = 100;
         return retv;

pool.instanceProvider = new ShipInstanceProvider();

Your instance provider just needs to instantiate…it doesn’t need to worry about the details of maintaining those instances. That’s all being taken care of by the pool itself.

I think that covers it. I haven’t actually drunk even a sip of whisky while writing this post, which feels wrong. But at least we have pools, and they most assuredly feel right.

Implicitly Delicious

One great new feature in Strange v0.7 (release candidate now on dev) is implicit bindings. This work comes to us courtesy of Strange super-contributor Will Corwin, author of Strange Signals. Implicit bindings adds a groovy mechanism for cleaning out the ‘routine’ mappings that sometimes clutter your Context.

As usual, let’s start with an illustrative example. Let’s say you’ve created an AvatarService for your game to handle the saving and retrieving of avatar data. Because you’re a diligent programmer, you also have an IAvatarService interface. Here’s the mapping as it would appear in your Context:


Awesome. You’re doing the good IoC thing: injecting and writing to the Interface rather than the concrete class. But, er, come over here where nobody can hear us. Now, between you, me and my ravenous DeathDroid, the truth is that you only have one AvatarService, right? Or you have one that you use 90 percent of the time? In fact, you probably have many classes like this, where the mappings are the same each and every time you build a new Context. These are routine mappings — bindings that look the same nearly every time you map them. Wouldn’t it be nice to have all the advantages of binding without cluttering up your Context with all this pro forma boilerplate? Don’t we all just want to walk into the Strange Bar and bark out “Gimme the usual?”

This is exactly what implicit bindings are for. By allowing you to specify default implementations, we can now reserve the Context only for mappings that are different from “yer usual.” For now, Implicit bindings allow you to do the following things:

  • Tag an interface with the class that implements it by default
  • Tag a class with one or more interface(s) it implements by default
  • Tag a View with the default Mediator
  • Tag a Mediator with a default View

Implicit Injection Bindings

The first two bullet points above describe injection bindings. For example, you could achieve our AvatarService binding by doing either of the following:

// Tagging an implementor
namespace com.example
    public class AvatarService : IAvatarService
        //body of the class

// Tagging an interface
namespace com.example
    public interface IAvatarService
        //body of the interface

While you can tag either Interface or Implementor, as a best practice we recommend tagging the Implementor. Tagging the Interface probably fits a special case for library distribution, but is not ideal for standard use. Note that there is a priority order to implicit injection binding, as follows:

  • Interfaces give way to
  • Implementors, which give way to
  • Explicit bindings in the Context.

Also note that you can create Singleton, named, single-Context and cross-Context bindings implicitly. You cannot yet create factory or value bindings (maybe in a future release).

Implicit Mediation Binding

We apply the same idea to Mediation.

// tagging a View
namespace com.example
    public class ShipView : View
        //body of the class

// tagging a Mediator
namespace com.example
    public class ShipMediator : Mediator
        public ShipView view { get; set; }
        //body of the class

As with injections, there’s an order of priority for Mediation bindings:

  • Views give way to
  • Mediators, which give way to
  • Explicit bindings in the Context.

We consider it best practice to tag the Mediator, not the View.

Magic: The Binding

Now, there is one more step you need to do to get all this automagic binding to work. Like Signals, Will’s made implicit bindings an opt-in feature, so you need to tell Strange (1) that you want to use it and (2) which namespaces you want scanned for binding. Yes, that’s right, implicit binding requires namespaces. The required code is simple (we suggest putting it at the top of your mapBindings method).

override protected void mapBindings()
    string[] namespaces = new string[]
    // add other bindings here

Scans include child namespaces, so if you scan “com.example”, the scan covers “com.example.myproject” and “com.example.myproject.services”, etc.

And there you go! Implicit bindings that go down smoother than a sherry-finished Balvenie.

On Xamarin, Unit Testing and Madness

This is part grouse, part warning so hopefully someone else is saved from falling into this trap.

So I’ll just get this off my chest right now. I don’t much care for Xamarin. Sure, it’s better than the version of MonoDevelop that Unity developers have been saddled with until the very recent release of Unity 4.3 (and I admit I’ve spent no time getting friendly with Unity’s updated version of MD), but to anyone used to Eclipse, Intelli-J or most any other IDE, it’s really a pretty poor candidate for serious developers IMO. It’s buggy, feature-poor, the tools are clunky and implementation is irregular. To be fair, as a Unity dev I’m not really using it for its intended function, i.e., building C#-based iOS and Android apps. So maybe I’m not their target audience.

But even with that as an introduction, my recent hair-pulling with Xamarin and unit testing took me by surprise. When developing Strange, I work almost exclusively in an NUnit testing environment. That means I’m not running an application per se, I’m just writing unit tests, watching them fail, then writing code to make them stop failing. And you receive the results in the form of a tested Inversion-of-Control framework.

Almost from the beginning, I’ve needed Console output to assist in that TDD approach. And I’ve not had it. I’ve scoured the documentation and the help boards but couldn’t figure out why it wouldn’t work for me. I found threads and docs and more docs but none of them adequately explained why a simple Console.WriteLine() never showed results in the Application Output pad. Two days ago, I posted my own thread on the Xamarin boards (yes, I should have done this sooner) and now finally, after struggling for over a month, I have an answer. Get this:

  1. If you’re unit testing, the Console output doesn’t go to Application Output, it gets redirected to Test Results.
  2. But you STILL won’t see that output unless you toggle both the ‘Output’ button and the toggle for Failed/Successful/Inconclusive Tests, as appropriate (oh, and they’re not on by default).
  3. This is documented…where? (I’ve just received a semi-official response and the answer is…nowhere)

Now I’m not arguing with the utility of being able to sift your test output. Sure, I’ll probably want to see output from my Failed Tests more often, and in those cases it’ll be nice to hide the Successful Test output. But does this really need to be in a special window? Should this be documented? Might Xamarin have contextual help or even a wiki?

Maybe I’m an idiot. It’s possible. We all do stupid stuff from time-to-time. But I feel roundly burned by an incredibly squirrelly implementation and inadequate documentation. And the bottom line is this: as things stand I will jump ship the moment someone offers me a more credible solution. And that doesn’t speak well for any product.