All posts

· 9 min read

Path · Ch. 17

Singleton: One Object and the Traps It Brings

We look at the Singleton pattern in C#, the simple version and the Lazy<T> version. Then we see why it is almost always better to create one object and pass it to whoever needs it.

On this page
  1. The problem: two objects that should be one
  2. The pattern: a single instance
  3. The Lazy<T> version
  4. The traps
  5. The alternative: create one and pass it in
  6. When NOT to use it
  7. Exercise
  8. Suggested solution
  9. Recap
  10. What’s next

Sooner or later you ask your code this question: how do I make sure only one object of this class exists? The corner store’s configuration, an order counter, a log of what happened. If every part of the program creates its own, each one sees different things.

The Singleton pattern answers that question, which is why it is the most famous pattern and also the most misused. In this chapter we see how to write it, and then why you will use it far less than you think.

The problem: two objects that should be one

Imagine the store has a configuration with the tax rate. This is what happens when everyone creates their own:

var a = new StoreConfig();
var b = new StoreConfig();

a.TaxRate = 0.115m;

Console.WriteLine($"a: {a.TaxRate:0.000}");
Console.WriteLine($"b: {b.TaxRate:0.000}");

class StoreConfig
{
    public decimal TaxRate { get; set; } = 0.10m;
}
a: 0.115
b: 0.100

You changed the rate on a, but b still has the old one. They are two different objects, each with its own copy of the data. If one part of the program charges 11.5% and another charges 10%, you have a bug that is hard to explain to a customer.

The pattern: a single instance

The Singleton idea has two pieces. First, the constructor is private, so nobody outside the class can call new. Second, the class keeps its only instance in a static member and hands it out to everyone:

var a = StoreConfig.Instance;
var b = StoreConfig.Instance;

a.TaxRate = 0.115m;

Console.WriteLine($"a: {a.TaxRate:0.000}");
Console.WriteLine($"b: {b.TaxRate:0.000}");
Console.WriteLine(object.ReferenceEquals(a, b));

class StoreConfig
{
    public static StoreConfig Instance { get; } = new StoreConfig();

    private StoreConfig() { }

    public decimal TaxRate { get; set; } = 0.10m;
}
a: 0.115
b: 0.115
True

a and b are the same reference, so a change shows up from both sides. ReferenceEquals asks whether two variables point to the same object, and here the answer is yes.

Remember from the classes chapter that static means the member belongs to the class, not to an object. That is why you can write StoreConfig.Instance without calling new first.

What if the program has several threads asking for the instance at the same time? .NET handles a static initializer like the one above for you: the runtime guarantees it runs exactly once. That guarantee is why this is the version I recommend to start with. The classic version from the books, with a hand-written if (instance == null), is not safe with several threads unless you add more code, and you do not need to write it.

The Lazy<T> version

The previous version creates the object when the class is first used. If creating it is expensive, or you want it not to happen until someone really asks, you can use Lazy<T>. A Lazy<T> stores how to create the object and creates it the first time you read .Value. By default it is safe with several threads.

Console.WriteLine("Program start");

var config = StoreConfig.Instance;
var other = StoreConfig.Instance;

Console.WriteLine(object.ReferenceEquals(config, other));

class StoreConfig
{
    private static readonly Lazy<StoreConfig> _instance =
        new(() => new StoreConfig());

    public static StoreConfig Instance => _instance.Value;

    private StoreConfig()
    {
        Console.WriteLine("Creating the configuration");
    }

    public decimal TaxRate { get; set; } = 0.10m;
}
Program start
Creating the configuration
True

Look at the order: the creation message comes after “Program start”, and only once even though we asked for the instance twice. The () => new StoreConfig() is a small nameless function you hand to Lazy; for now just read it as “this is how the object gets created”.

That is all you need to write a Singleton. Now comes the important part.

The traps

The problem with Singleton is not how it is written but what it does to the rest of your code. Look at a class that charges tax using the global configuration:

StoreConfig.Instance.TaxRate = 0.115m;

var calc = new Calculator();
Console.WriteLine($"Test 1: {calc.TotalWithTax(100m):0.00}");

var calc2 = new Calculator();
Console.WriteLine($"Test 2: {calc2.TotalWithTax(100m):0.00}");

class StoreConfig
{
    public static StoreConfig Instance { get; } = new StoreConfig();

    private StoreConfig() { }

    public decimal TaxRate { get; set; } = 0.10m;
}

class Calculator
{
    public decimal TotalWithTax(decimal subtotal)
    {
        return subtotal * (1 + StoreConfig.Instance.TaxRate);
    }
}
Test 1: 111.50
Test 2: 111.50

“Test 2” expected the default tax, 10%, so 110.00. It got 111.50 because the previous test left the rate changed. All three traps are here together:

  • Hidden global state. Any part of the program can change TaxRate, and every other part finds out without warning. When something goes wrong, you have to search the whole codebase for who touched it.
  • Hidden dependencies. Look at new Calculator(). Nothing in its signature says it needs a configuration. You have to read the body of every method to find out.
  • Hard to test. You cannot give Calculator its own configuration for a test, because it always goes looking for the global one. And since the object lives as long as the program does, the result of one test leaks into the next, as you just saw.

The alternative: create one and pass it in

What you really needed was one shared configuration object. You did not need the class to enforce it. You can create one in Program.cs and hand it to whoever uses it:

var config = new StoreConfig { TaxRate = 0.115m };
var calc = new Calculator(config);
Console.WriteLine($"Test 1: {calc.TotalWithTax(100m):0.00}");

var testConfig = new StoreConfig();
var calc2 = new Calculator(testConfig);
Console.WriteLine($"Test 2: {calc2.TotalWithTax(100m):0.00}");

class StoreConfig
{
    public decimal TaxRate { get; set; } = 0.10m;
}

class Calculator
{
    private readonly StoreConfig _config;

    public Calculator(StoreConfig config)
    {
        _config = config;
    }

    public decimal TotalWithTax(decimal subtotal)
    {
        return subtotal * (1 + _config.TaxRate);
    }
}
Test 1: 111.50
Test 2: 110.00

Now the dependency is visible in the constructor: Calculator tells you it needs a StoreConfig. Each test builds its own and they do not contaminate each other. And in the real application, the same config object is passed to every class that needs it, so there is still a single instance in use. You got what Singleton was after without the global state.

A preview: when you get to ASP.NET Core, the framework comes with a mechanism called dependency injection. You tell it “I want a single instance of this class for the whole application” and it creates it and hands it to whoever asks. That is called registering it as a singleton. It is the same idea as this chapter, with the framework doing the passing for you. You do not need to set it up yet; just know that when it shows up, you already understand the concept.

When NOT to use it

Almost always. If that surprises you, it is because Singleton is easy to write and feels tidy, but it bills you later.

  • Do not use it because “we only need this once”. That one object exists today does not mean the class should forbid a second one. Tomorrow you may need a different configuration for a test or for another store.
  • Do not use it to hold data that changes, like the cart or the current user. That is where global state does the most damage.
  • Do not use it to save yourself from writing parameters. Passing the object through the constructor costs one line and buys you clarity.

There are cases where a single shared object makes sense, and you saw one: the configuration. But the sensible way is to create it once and pass it in, not to make the class force it on itself.

Exercise

This program generates order numbers with a Singleton. Convert it: remove the Singleton, make NumberGenerator creatable with new, and pass it to OrderService through the constructor. Then create a second service with its own generator and check that its first order is number 1.

var service = new OrderService();
Console.WriteLine(service.CreateOrder("Coffee"));
Console.WriteLine(service.CreateOrder("Bread"));

class NumberGenerator
{
    public static NumberGenerator Instance { get; } = new NumberGenerator();

    private NumberGenerator() { }

    private int _last;

    public int Next()
    {
        _last++;
        return _last;
    }
}

class OrderService
{
    public string CreateOrder(string product)
    {
        int number = NumberGenerator.Instance.Next();
        return $"Order #{number}: {product}";
    }
}

Suggested solution

var generator = new NumberGenerator();
var service = new OrderService(generator);
Console.WriteLine(service.CreateOrder("Coffee"));
Console.WriteLine(service.CreateOrder("Bread"));

var newService = new OrderService(new NumberGenerator());
Console.WriteLine(newService.CreateOrder("Milk"));

class NumberGenerator
{
    private int _last;

    public int Next()
    {
        _last++;
        return _last;
    }
}

class OrderService
{
    private readonly NumberGenerator _generator;

    public OrderService(NumberGenerator generator)
    {
        _generator = generator;
    }

    public string CreateOrder(string product)
    {
        int number = _generator.Next();
        return $"Order #{number}: {product}";
    }
}
Order #1: Coffee
Order #2: Bread
Order #1: Milk

The first two orders share a generator, so the numbering continues. The third uses another generator and starts over. With the Singleton, that second numbering was impossible without restarting the program.

Recap

  • A Singleton guarantees a single instance: a private constructor and the instance stored in a static member.
  • A static initializer is already safe with several threads, and Lazy<T> lets you create the object only when someone asks for it.
  • Its traps are hidden global state, hidden dependencies, and tests that contaminate each other.
  • It is almost always better to create one instance and pass it through the constructor. ASP.NET Core does that passing for you when you register something as a singleton.

What’s next

In the next chapter we look at the Repository pattern: how to hide behind an interface where your data lives, so the rest of the program does not know whether it sits in a list or in a database.

If something was unclear or you want to share your exercise, DM me on Instagram or come by the Discord community.