Creational patterns: singleton, factory, builder
Creational patterns control how objects get made. Calling new ConcreteClass() everywhere ties code to one implementation, scatters construction rules, and makes objects with many options hard to create correctly. The three patterns on this page solve the problems that come up most: exactly one shared instance (singleton), choosing which class to create at run time (factory), and assembling an object with many optional parts (builder).
In modern .NET the dependency injection container already does much of this work, so each section shows the classic pattern and then how it looks with Microsoft.Extensions.DependencyInjection. The samples share one invented OrdersPortal domain. They are C# file-based programs: save as a .cs file and run dotnet run file.cs with the .NET 10 SDK; all were run with SDK 10.0.115.
Topics on this page
Section titled “Topics on this page”| Pattern | Category | Use it when |
|---|---|---|
| Singleton | GoF creational | Exactly one instance must be shared, and it is safe to share. |
| Factory | GoF creational (Factory Method, Abstract Factory) | The class to create depends on run-time data or a subclass. |
| Builder | GoF creational | An object has many optional parts or must be validated as a whole. |
The patterns come from Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, Helm, Johnson and Vlissides, 1994), often called the Gang of Four (GoF) book. The design patterns overview lists all three categories.
Singleton
Section titled “Singleton”The Singleton pattern ensures a class has only one instance and gives global access to it. Typical candidates are expensive, stateless or read-mostly objects: configuration snapshots, caches, a pool or a client that is designed to be shared. The classic C# implementation makes the constructor private and exposes a static Instance property backed by Lazy<T>, which is thread-safe by default: if several threads ask at once, the factory still runs once.
In application code, prefer letting the DI container own the single instance with services.AddSingleton<IExchangeRates, CachedExchangeRates>(). You still get one instance, but consumers receive it through their constructor, so the dependency is visible and tests can pass a fake. Keep the static form for the rare cases with no container (a low-level library, a source generator) or for truly global, immutable data. In TypeScript and Node.js, a module-level export const is the idiomatic singleton because modules are evaluated once.
#:package Microsoft.Extensions.DependencyInjection@10.0.0using Microsoft.Extensions.DependencyInjection;
// Classic singleton: thread-safe lazy creation with Lazy<T>.var tasks = Enumerable.Range(0, 8).Select(_ => Task.Run(() => PricingRules.Instance)).ToArray();var instances = await Task.WhenAll(tasks);Console.WriteLine($"Distinct instances: {instances.Distinct().Count()}, created {PricingRules.CreatedCount} time(s)");Console.WriteLine($"Free shipping from: {PricingRules.Instance.FreeShippingThreshold:0.00}");
// Preferred in .NET apps: let the container own the single instance.var services = new ServiceCollection();services.AddSingleton<IExchangeRates, CachedExchangeRates>();services.AddTransient<CheckoutService>();using var provider = services.BuildServiceProvider();
var first = provider.GetRequiredService<CheckoutService>();var second = provider.GetRequiredService<CheckoutService>();Console.WriteLine($"Same rates object: {ReferenceEquals(first.Rates, second.Rates)}; 100 USD = {first.Convert(100m, "EUR"):0.00} EUR");
public sealed class PricingRules{ private static readonly Lazy<PricingRules> _instance = new(() => new PricingRules()); private static int _created;
private PricingRules() { Interlocked.Increment(ref _created); FreeShippingThreshold = 50m; // loaded from configuration in a real app }
public static PricingRules Instance => _instance.Value; public static int CreatedCount => _created; public decimal FreeShippingThreshold { get; }}
public interface IExchangeRates { decimal Rate(string currency); }public sealed class CachedExchangeRates : IExchangeRates{ private readonly Dictionary<string, decimal> _rates = new() { ["EUR"] = 0.92m, ["GBP"] = 0.79m }; public decimal Rate(string currency) => _rates[currency];}
public sealed class CheckoutService(IExchangeRates rates){ public IExchangeRates Rates => rates; public decimal Convert(decimal usd, string currency) => usd * rates.Rate(currency);}Output (exchange rates are illustrative):
Distinct instances: 1, created 1 time(s)Free shipping from: 50.00Same rates object: True; 100 USD = 92.00 EURPitfalls:
- Hidden global state. Static singletons are reachable from anywhere, carry state between unit tests and make dependencies invisible. Prefer
AddSingletonand constructor injection. - Mutable shared state without locking. A singleton is shared by every request thread; use immutable data, concurrent collections or explicit synchronization.
- Singleton holding scoped services. A singleton that captures a
DbContextkeeps one context for the whole app. See captive dependencies.
Factory
Section titled “Factory”Factory patterns put the decision of which class to instantiate in one place. Factory Method (GoF) declares an abstract creation method in a base class whose workflow uses the product, and lets each subclass override that method to choose the concrete product. Abstract Factory (GoF) creates families of related objects (a light-theme button, input and dialog) behind one interface so they always match. The simple factory, not a GoF pattern but the most common in practice, is a method that takes a key or some data and returns the right implementation.
In .NET the container is itself a factory. Since .NET 8, keyed services let you register several implementations of one interface under different keys and resolve one by key, which removes most hand-written switch factories. A small factory class around GetKeyedService still earns its place when you need a clear error for unknown keys, or when callers should not depend on IServiceProvider directly. Delegate factories (Func<string, IPaymentProcessor>) are another option.
#:package Microsoft.Extensions.DependencyInjection@10.0.0using Microsoft.Extensions.DependencyInjection;
// Factory Method: the base class runs the workflow, subclasses decide what to create.NotificationSender[] senders = [new EmailNotificationSender(), new SmsNotificationSender()];foreach (var sender in senders) sender.NotifyShipped(orderId: 1001, recipient: sender is SmsNotificationSender ? "+1-555-0100" : "dana@example.test");
// Simple factory over the DI container: keyed services (.NET 8+) pick an implementation by key.var services = new ServiceCollection();services.AddKeyedSingleton<IPaymentProcessor, CardProcessor>("card");services.AddKeyedSingleton<IPaymentProcessor, InvoiceProcessor>("invoice");services.AddSingleton<PaymentProcessorFactory>();using var provider = services.BuildServiceProvider();
var factory = provider.GetRequiredService<PaymentProcessorFactory>();foreach (var method in new[] { "card", "invoice", "crypto" }){ try { Console.WriteLine(factory.Create(method).Charge(1001, 128.48m)); } catch (NotSupportedException ex) { Console.WriteLine(ex.Message); }}
// ---------- Factory Method ----------public interface INotification { string Send(string recipient, string text); }public sealed class EmailNotification : INotification{ public string Send(string recipient, string text) => $"email to {recipient}: {text}";}public sealed class SmsNotification : INotification{ public string Send(string recipient, string text) => $"sms to {recipient}: {text.Replace(" and is on its way", "")}";}
public abstract class NotificationSender{ protected abstract INotification CreateNotification(); // the factory method
public void NotifyShipped(int orderId, string recipient) => Console.WriteLine(CreateNotification().Send(recipient, $"Order {orderId} has shipped and is on its way"));}public sealed class EmailNotificationSender : NotificationSender{ protected override INotification CreateNotification() => new EmailNotification();}public sealed class SmsNotificationSender : NotificationSender{ protected override INotification CreateNotification() => new SmsNotification();}
// ---------- Factory over keyed services ----------public interface IPaymentProcessor { string Charge(int orderId, decimal amount); }public sealed class CardProcessor : IPaymentProcessor{ public string Charge(int orderId, decimal amount) => $"card: charged {amount:0.00} for order {orderId}";}public sealed class InvoiceProcessor : IPaymentProcessor{ public string Charge(int orderId, decimal amount) => $"invoice: issued {amount:0.00} due in 30 days for order {orderId}";}
public sealed class PaymentProcessorFactory(IServiceProvider services){ public IPaymentProcessor Create(string method) => services.GetKeyedService<IPaymentProcessor>(method) ?? throw new NotSupportedException($"Payment method '{method}' is not supported");}Output:
email to dana@example.test: Order 1001 has shipped and is on its waysms to +1-555-0100: Order 1001 has shippedcard: charged 128.48 for order 1001invoice: issued 128.48 due in 30 days for order 1001Payment method 'crypto' is not supportedPitfalls:
- A growing
switch. A factory that must be edited for every new type violates open/closed and becomes a merge-conflict hot spot. Let registrations (keyed services, a dictionary of creators) carry the mapping. - Service locator in disguise. Injecting
IServiceProviderinto business classes so they can “create what they need” hides dependencies. Confine it to a dedicated factory at the composition boundary. - Factories for one implementation. If there is only ever one concrete class,
newor plain DI registration is simpler.
Builder
Section titled “Builder”The Builder pattern separates constructing a complex object from its final representation. Instead of a constructor with eleven parameters (several of them null and two adjacent bools nobody can tell apart), callers use named, chainable methods (WithLine, Cc, AsHtml) and finish with Build(). Builders shine when an object has many optional parts, when parts must be added in steps (lines, headers, attachments), or when the whole object must be validated before it exists. The product can then be immutable, because all mutation happens in the builder.
Modern C# reduces the need for builders for simple data: object initializers, required members and records with with expressions cover many cases. Builders remain the right tool for step-by-step assembly and cross-field validation, and for the test data builder variant: a builder with sensible defaults that lets each test override only the fields it cares about, so tests stay readable and do not break when an unrelated property is added. ASP.NET Core itself uses builders (WebApplication.CreateBuilder, ResiliencePipelineBuilder).
var email = new ConfirmationEmailBuilder("dana@example.test", orderId: 1001) .WithSubject("Your OrdersPortal order is confirmed") .WithLine("Keyboard", 2, 49.99m) .WithLine("USB-C cable", 3, 9.50m) .Cc("billing@example.test") .AsHtml() .Build();
Console.WriteLine($"To: {email.To} (cc {string.Join(", ", email.Cc)})");Console.WriteLine($"Subject: {email.Subject}; html: {email.IsHtml}; total: {email.Total:0.00}");
try{ new ConfirmationEmailBuilder("dana@example.test", orderId: 1002).Build();}catch (InvalidOperationException ex){ Console.WriteLine($"Build failed: {ex.Message}");}
// Test data builder: sensible defaults, override only what a test cares about.var vipOrder = new OrderBuilder().ForCustomer("vip@example.test").WithTotal(950m).Build();Console.WriteLine(vipOrder);
// ---------- The product: immutable once built ----------public sealed record ConfirmationEmail( string To, IReadOnlyList<string> Cc, string Subject, bool IsHtml, IReadOnlyList<(string Product, int Quantity, decimal UnitPrice)> Lines){ public decimal Total => Lines.Sum(l => l.Quantity * l.UnitPrice);}
// ---------- The builder: mutable, fluent, validates in Build() ----------public sealed class ConfirmationEmailBuilder(string to, int orderId){ private readonly List<string> _cc = []; private readonly List<(string, int, decimal)> _lines = []; private string _subject = $"Order {orderId} confirmed"; private bool _isHtml;
public ConfirmationEmailBuilder WithSubject(string subject) { _subject = subject; return this; } public ConfirmationEmailBuilder Cc(string address) { _cc.Add(address); return this; } public ConfirmationEmailBuilder AsHtml() { _isHtml = true; return this; } public ConfirmationEmailBuilder WithLine(string product, int quantity, decimal unitPrice) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity); _lines.Add((product, quantity, unitPrice)); return this; }
public ConfirmationEmail Build() { if (_lines.Count == 0) throw new InvalidOperationException($"order {orderId} has no lines to confirm"); return new ConfirmationEmail(to, [.. _cc], _subject, _isHtml, [.. _lines]); }}
public sealed record Order(int Id, string CustomerEmail, decimal Total, string Status);
public sealed class OrderBuilder{ private int _id = 1; private string _email = "customer@example.test"; private decimal _total = 10m; private string _status = "Placed";
public OrderBuilder WithId(int id) { _id = id; return this; } public OrderBuilder ForCustomer(string email) { _email = email; return this; } public OrderBuilder WithTotal(decimal total) { _total = total; return this; } public OrderBuilder Shipped() { _status = "Shipped"; return this; } public Order Build() => new(_id, _email, _total, _status);}Output:
To: dana@example.test (cc billing@example.test)Subject: Your OrdersPortal order is confirmed; html: True; total: 128.48Build failed: order 1002 has no lines to confirmOrder { Id = 1, CustomerEmail = vip@example.test, Total = 950, Status = Placed }Pitfalls:
- Builders for three-property objects. A record with named arguments or an object initializer is clearer and has no extra class to maintain.
- Reusing a builder. A builder that keeps its lists after
Build()can leak state into the next object; copy collections into the product (as the sample does with[.. _cc]) or create a new builder each time. - Validation spread across setters. Validate the whole object in
Build(), where all fields are known.
Choosing between them
Section titled “Choosing between them”| Problem | Pattern | Modern .NET form |
|---|---|---|
| One shared instance | Singleton | AddSingleton in DI |
| Pick an implementation by key or configuration | Simple factory | Keyed services, Func<> factory |
| Subclass decides what to create inside a fixed workflow | Factory Method | Abstract or virtual creation method |
| Families of objects that must match | Abstract Factory | Interface with one Create... method per product |
| Many optional parts, step-by-step assembly, whole-object validation | Builder | Fluent builder, test data builder |
| Few properties, no cross-field rules | None | Record or object initializer with required members |
Interview questions
Section titled “Interview questions”How do you make a singleton thread-safe in C#?
Use Lazy<T> (thread-safe by default) or a static readonly field initialized by the runtime’s type initializer. Hand-written double-checked locking is easy to get wrong and unnecessary in .NET.
Why is a DI-registered singleton usually better than the Singleton pattern? It gives the same single instance but through constructor injection: dependencies are explicit, tests can substitute a fake, the lifetime is managed and disposed by the container, and scope validation catches captive dependencies.
What is the difference between Factory Method and Abstract Factory? Factory Method is one overridable method that creates one product, chosen by subclassing. Abstract Factory is an object with several creation methods that produce a family of related products which must be used together.
When would you choose a builder over a constructor or object initializer?
When construction has many optional parts, happens in steps, or needs validation across several fields before the object may exist. For simple immutable data, records and required members are enough.
Senior scenario: OrdersPortal must support a new payment provider per country, configured at deploy time, without code changes in checkout. How would you structure creation?
Define an IPaymentProcessor interface, implement each provider in its own class (or assembly), and register them as keyed services under provider names, with the country-to-provider mapping in configuration validated at startup (ValidateOnStart). A small PaymentProcessorFactory resolves by key and fails clearly for unknown providers. Checkout depends only on the factory or on the processor resolved for the current order, so adding a provider means a new class, a registration and configuration, not a change to checkout.
Related pages
Section titled “Related pages”- Design patterns overview
- Structural and behavioral patterns: adapter, decorator, repository, strategy, observer
- .NET core features: dependency injection
- Unit testing: test data builders in practice.