Subclassed singleton instance

I couldn’t really think of a good explanatory title for this post, so I guess I’ll just have to explain. I’m setting up a dependency injection resolver using NInject, and I’m trying to centralise the implementation so it can be reused in the various layers of the application, but I want each application to be able to configure it in isolation of every other layer. I’m still not quite sure that I’m explaining what I want correctly, so let me try explaining it this way.

In App.Core. I want to create the InjectorBase class that every injection implementation derives from. Then, for example, in the App.UI I want to create a UserInterfaceInjector that descends from InjectorBase, but I only want the subclass to supply configuration. Then in App.Services I can create a ServicesInjector that also descends from InjectorBase, and again, only supplies configuration.

The next trick to this is, I want the dependency injection to be through a singleton. Yes, yes, singletons are evil etc. In this case, it’s being used for what I consider a correct purpose (as a service locator), and not some sort of global variable hold-all. So, in some random piece of code in App.Services, I want to be able to do something like this:

public void SomeMethodThatDoesSomethingTo(Some variable)
{
    var aRepository = ServicesInjector.Default.Get<IARepository>();
    aRepository.Add(variable);
}

And, conversely, in the App.UI I want to be able to do this:

public void SomeMethodThatLocatesAServiceImplementation()
{
    var aService = UserInterfaceInjector.Default.Get<IAService>();
    aService.DoSomethingMostLikelyAsynchronously();
}

It all seems fairly straight forward, yes? Well, it winds up not being too difficult, but one of the first problems you’ll run into relates to inheritance and the static keyword. Basically, you can’t. Which actually makes sense if you care to try and understand it. Anything static is of the class, not of an instance of the class. If you create a subclass, it’s new class, so the static thing doesn’t follow you. Why do we need the static keyword? The singleton. Here’s an example (simple) singleton implementation.

public class MySingleton
{
    private static MySingleton _default;

    public static MySingleton Default
    {
        get { return _default ?? _default = new MySingleton(); }
    }

    public string SayHello()
    {
        return "Hello!";
    }
}

In order to supply a reference to an instance without maintaining that reference in another class, we have to use a static field (to hold the reference) and a static property (to get at the static field).

Where I wanted to take this that was a bit out of the ordinary, is I wanted the singleton in the base class so implementors didn’t have to think about all that plumbing. This means making the base class abstract (so it can’t be directly instantiated) and then providing an abstract method that returns a container configuration. Then all the subclasses have to do is inherit from the base class and then provide an implementation of the abstract method.

The next problem is, the configuration method is an abstract method of the base class, and not static, but the point of creation of the class is in a static property get method. How do you call an instance method of a class to obtain configuration you need at creation time without an instance of the class? Well, you can’t. Now, obviously I’ve solved this problem, otherwise we’d be at the end of this post.

The gist of it involves breaking a cardinal rule of C# object creation: Don’t call virtual methods in a constructor. The reasoning behind this is C# initialisers (initializers for the Americans amongst us) run in order of farthest child back up to the base class, but the constructors run from the base class to the farthest child. Here’s a bit more information. The trick to overcoming the actual problem was to use the Activator class. This involves a bit of genericism of the base class to ensure the child class is being instantiated, which then allows us to call the virtual method with abandon. So the base class now looks like this:

abstract class BaseClass<T> : IHello where T: IHello
{
    private static IHello _default;
    private readonly string _message = "Hello from the base class.";

    public static IHello Default
    {
        get { return _default ??
                    (_default = Activator.CreateInstance<T>()); }
    }

    protected BaseClass()
    {
        _message = GetMessage();
    }

    public void SayHello()
    {
        Console.WriteLine(_message);
    }

    public abstract string GetMessage();
}

Here’s IHello, in case you couldn’t figure it out:

interface IHello
{
    void SayHello();
}

Finally, here’s how the implementors of the base class look:

class ChildClass : BaseClass<ChildClass>;
{
    public sealed override string GetMessage()
    {
        return "Hello from the child class.";
    }
}

You can tie all this together in a console application with a bit of this magic:

class Program
{
    static void Main(string[] args)
    {
        ChildClass.Default.SayHello();
        Console.ReadKey(true);
    }
}

I’m about to roll this into the code. The spike seems to work without any problems (other than ReSharper warning me about my virtual method call in the constructor), but until I put it into the application code I won’t really know if it’s 100%. Let me know if you spot anything silly, won’t you?

Oh, here’s a link to the sample code if you want it.