TL;DR — Intent and the Core Trade-off
Abstract Factory gives a client one interface for creating an entire family of related objects, so the client never names a concrete class and never has to know which family it's actually assembling with. Swap the factory implementation and every product it hands out changes together, consistently, with zero edits at the call site.
The single rule that defines the pattern: a client depends on one factory interface and a set of product interfaces, and constructs nothing with new beyond that factory itself. If a client is calling new WindowsButton() anywhere alongside an IGuiFactory, the pattern has already leaked.
You buy consistency across a product family and a single seam for swapping the whole family at once. You pay with an interface that grows every time you add a new product — one method added to IGuiFactory becomes an override in every concrete factory you've ever written, whether or not that factory cares about the new product.
That cost isn't hypothetical. It's the whole reason a strong current of criticism (§12) argues that in a codebase already using a DI container, Abstract Factory is frequently the wrong tool — keyed services and composition root wiring solve the "give me the right family" problem without the interface-explosion cost. Hold both truths at once: the pattern is real, well-defined, and occasionally exactly right; it is also frequently reached for out of habit when a simpler mechanism would do.
Origins, Classification, and the Problem It Solves
Abstract Factory is a Creational, object-scope pattern in the 1994 Gang of Four catalogue — object-scope because the family relationships are wired up between object instances at runtime, not baked into a class hierarchy at compile time the way Factory Method's class-scope variant is. It first appeared under the name "Kit" in earlier Smalltalk literature; GoF renamed it and generalized it for statically-typed C++ codebases where swapping an entire windowing toolkit (Motif vs. Presentation Manager, in the book's own example) at link time was a genuine, everyday problem.
The pain it was reacting to: a UI toolkit era where "portable across platforms" meant scattering #ifdef blocks — or their C# equivalent, giant switch statements on an enum — through every place a widget got created. Here's that mess, recognizably:
// UiKit/DialogRenderer.cs — before: switch-per-platform, repeated everywhere a widget is built
public sealed class DialogRenderer
{
private readonly UiTheme _theme; // enum: Windows, MacOs, Linux
public DialogRenderer(UiTheme theme) => _theme = theme;
public void RenderConfirmDialog(string message)
{
// Every widget site repeats this switch. Add a Linux GTK theme next
// sprint and you must find and edit every one of them correctly.
Button okButton = _theme switch
{
UiTheme.Windows => new WindowsButton("OK"),
UiTheme.MacOs => new MacButton("OK"),
_ => throw new NotSupportedException($"Unhandled theme {_theme}")
};
Checkbox rememberChoice = _theme switch
{
UiTheme.Windows => new WindowsCheckbox("Remember my choice"),
UiTheme.MacOs => new MacCheckbox("Remember my choice"),
_ => throw new NotSupportedException($"Unhandled theme {_theme}")
};
// Nothing stops a Windows button from pairing with a Mac checkbox if
// someone forgets to update one switch after adding a theme — the
// "family" is only a convention living in the programmer's head.
okButton.Draw();
rememberChoice.Draw();
}
}
Two failures compound here: the switch recompiles and grows at every call site whenever a new platform is added, and nothing enforces that the button and checkbox actually come from the same family — a copy-paste slip silently mixes a Windows control with a Mac one, and it compiles fine.
Structure and Participants
| Participant | Role | Belongs in it | Must never be in it |
|---|---|---|---|
| AbstractFactory | Declares one creation method per product in the family | Only creation signatures | Business logic, shared state |
| ConcreteFactory | Produces one consistent family (one per variant) | Wiring to concrete product constructors | Logic unrelated to construction |
| AbstractProduct | Declares the operations a product family member supports | The product's public contract | Any reference back to its factory |
| ConcreteProduct | One variant's implementation of a product | Variant-specific behaviour | Knowledge of sibling products' concrete types |
| Client | Consumes only the abstract factory and abstract products | Calls to factory methods, product operations | Any new WindowsButton()-style construction |
The membership test: does this class produce (or get produced as) one coherent, interchangeable-as-a-set variant? If a class varies independently of the rest of the family — a logging strategy that's identical regardless of which UI theme is active — it isn't a family member, no matter how tempting it is to add a CreateLogger() method to the factory just because the factory is already there.
The Central Mechanic
The trick is narrower than it looks: the client depends on exactly one factory reference, obtained once, and every product it subsequently touches is a downstream consequence of that single choice. There's no double dispatch here and no wrapper trick — the mechanic is closure over a choice. Pick MacFactory once, and every button, checkbox, and dialog produced from it is guaranteed consistent, because they all trace back to the one object.
Compare that to calling four separate static factory methods with a theme parameter passed to each — nothing there prevents the parameter from drifting between calls. Here, the family choice is made exactly once, and the type system enforces the rest.
Implementation in C# — Naive, Then Idiomatic
Pass one — the textbook translation
// UiKit/IGuiFactory.cs — naive, literal GoF translation
namespace UiKit
{
public interface IGuiFactory
{
IButton CreateButton();
ICheckbox CreateCheckbox();
}
public interface IButton { void Draw(); }
public interface ICheckbox { void Draw(); }
public class WindowsFactory : IGuiFactory
{
public IButton CreateButton() { return new WindowsButton(); }
public ICheckbox CreateCheckbox() { return new WindowsCheckbox(); }
}
public class WindowsButton : IButton
{
public void Draw() { Console.WriteLine("Rendering a Windows-styled button"); }
}
public class WindowsCheckbox : ICheckbox
{
public void Draw() { Console.WriteLine("Rendering a Windows-styled checkbox"); }
}
}
This works and is honest, but it's 2026-flavourless: no nullable annotations, mutable-by-default classes, no primary constructors, and manual new-ing of the factory somewhere the client lives.
Pass two — the version an experienced .NET developer writes in 2026
// UiKit/IGuiFactory.cs — idiomatic C# 14 / .NET 10
namespace UiKit;
public interface IGuiFactory
{
IButton CreateButton();
ICheckbox CreateCheckbox();
}
public interface IButton { void Draw(); }
public interface ICheckbox { void Draw(); }
// sealed by default: this factory has no reason to be extended via inheritance
public sealed class WindowsFactory : IGuiFactory
{
public IButton CreateButton() => new WindowsButton();
public ICheckbox CreateCheckbox() => new WindowsCheckbox();
}
// a record for a stateless product: value-equality is free and correct here
public sealed record WindowsButton : IButton
{
public void Draw() => Console.WriteLine("Rendering a Windows-styled button");
}
public sealed record WindowsCheckbox : ICheckbox
{
public void Draw() => Console.WriteLine("Rendering a Windows-styled checkbox");
}
// composition root — the ONLY place that ever chooses a concrete factory
public static class UiKitRegistration
{
public static IServiceCollection AddUiKit(this IServiceCollection services, UiTheme theme)
{
services.AddSingleton<IGuiFactory>(theme switch
{
UiTheme.Windows => new WindowsFactory(),
UiTheme.MacOs => new MacFactory(),
_ => throw new NotSupportedException($"Unhandled theme {theme}")
});
return services;
}
}
Three divergences worth calling out specifically. Sealed by default: concrete factories and products are leaf types; nobody should be subclassing WindowsButton, and sealing documents that intent and lets the JIT devirtualize. Records for stateless products: a product with no mutable state is a natural record — value equality is a useful, free side-effect for anything you'll compare in tests. The switch lives in exactly one place — the composition root — rather than a Simple-Factory static method scattered wherever a factory is first needed; this is the one switch the pattern is supposed to eliminate everywhere except here.
Variations and Modern .NET Idioms
The classic form — one interface, N concrete factory classes, manual composition-root switch — is not the only shape this takes in current .NET, and for many codebases it's no longer the best default.
| Variation | How it works | When it's the better fit |
|---|---|---|
| Classic concrete-factory classes | One class per family, each implementing the shared factory interface | Family count is small and stable; factories carry real construction logic beyond a constructor call |
Func<T>-based product delegates | The "factory" is a small object holding several Func<IButton>-style delegates instead of a named interface | Family membership is genuinely just "which constructor to call" with no extra behaviour |
| Keyed DI services (.NET 8+) | IServiceProvider.GetRequiredKeyedService<T>(key) resolves a specific implementation per product, per family key | The container already owns the object graph; adding a bespoke factory interface duplicates what the container does natively |
The honest observation: keyed services have absorbed a large share of what Abstract Factory used to be reached for. When "the family" is just "which registered implementation to hand back," the container already knows how to do that without an extra interface layer — see §7 and §12 for the concrete comparison and the disagreement it produces.
// UiKit/KeyedRegistration.cs — the family expressed as keyed services instead
services.AddKeyedSingleton<IButton, WindowsButton>(UiTheme.Windows);
services.AddKeyedSingleton<IButton, MacButton>(UiTheme.MacOs);
services.AddKeyedSingleton<ICheckbox, WindowsCheckbox>(UiTheme.Windows);
services.AddKeyedSingleton<ICheckbox, MacCheckbox>(UiTheme.MacOs);
// consumer resolves the family member it needs, keyed by the active theme
public sealed class DialogRenderer(
[FromKeyedServices(typeof(UiTheme))] IButton button,
[FromKeyedServices(typeof(UiTheme))] ICheckbox checkbox)
{
public void Render() { button.Draw(); checkbox.Draw(); }
}
Notice what's lost as well as gained: there is no single object embodying "the Mac family" anymore — consistency has to be enforced by registering every keyed pair correctly, rather than by construction. For two products that's a wash; for a family of eight it's a real risk the classic form doesn't have.
Where .NET Itself Uses It
ILoggerFactory is the cleanest real-world instance: ILoggerFactory.CreateLogger(string categoryName) hands back an ILogger whose concrete behaviour — console, file, Application Insights, or all three — is entirely determined by how the factory itself was configured at startup, never by the calling code.
// Direct use of the real BCL factory type
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
builder.AddDebug();
});
ILogger logger = loggerFactory.CreateLogger("Ordering.PricingService");
logger.LogInformation("Quote {QuoteId} priced at {Total:C}", quoteId, total);
The mapping: ILoggerFactory is the AbstractFactory, the console/debug/App-Insights provider configuration is the concrete factory's "family," and every ILogger handed out shares that family's sinks and formatting without the caller ever choosing a provider. System.Data.Common.DbProviderFactory is the older, more literal example — DbProviderFactory.CreateConnection(), CreateCommand(), and CreateParameter() together produce a fully consistent ADO.NET object family for one database engine, selected once by provider name.
Worth flagging as the controversial relative rather than a clean example: IServiceProvider.GetService(Type) resolution is structurally a Service Locator, not Abstract Factory — the client asks a general-purpose container for "give me one of these" rather than depending on a narrow, purpose-built factory interface. The difference matters because Service Locator hides a class's real dependencies from its constructor signature, which is exactly the dependency an Abstract Factory is supposed to make explicit.
Runtime Flows
Real-World Worked Examples — Three
1. Payments — regional payment-provider families
A checkout service must charge, refund, and tokenize cards through one of several regional payment providers, and every operation for a given transaction must go through the same provider.
// Payments/IPaymentProviderFactory.cs
public interface IPaymentProviderFactory
{
IChargeGateway CreateChargeGateway();
ITokenVault CreateTokenVault();
}
public sealed class StripeProviderFactory : IPaymentProviderFactory
{
public IChargeGateway CreateChargeGateway() => new StripeChargeGateway();
public ITokenVault CreateTokenVault() => new StripeTokenVault();
}
public sealed class AdyenProviderFactory : IPaymentProviderFactory
{
public IChargeGateway CreateChargeGateway() => new AdyenChargeGateway();
public ITokenVault CreateTokenVault() => new AdyenTokenVault();
}
public sealed class CheckoutService(IPaymentProviderFactory providerFactory)
{
public async Task<ChargeResult> ChargeAsync(Order order, CancellationToken ct)
{
var gateway = providerFactory.CreateChargeGateway();
var vault = providerFactory.CreateTokenVault();
var token = await vault.TokenizeAsync(order.Card, ct);
return await gateway.ChargeAsync(token, order.Total, ct);
}
}
2. Notifications — channel-family bundles (a slightly uncomfortable fit)
A notification service sends both a transactional message and an audit-log entry through one channel — email+inbox-copy, or SMS+delivery-receipt — and the two must be created consistently.
// Notifications/IChannelFactory.cs
public interface IChannelFactory
{
IMessageSender CreateSender();
IDeliveryReceipt CreateReceiptWriter();
}
public sealed class EmailChannelFactory : IChannelFactory
{
public IMessageSender CreateSender() => new SmtpMessageSender();
public IDeliveryReceipt CreateReceiptWriter() => new InboxCopyWriter();
}
Where this is honestly a stretch: the sender and receipt-writer here don't vary together in any deep sense — an SMS sender and an inbox-copy writer could be paired perfectly well; there is no real coupling forcing the family. A single NotificationChannel record holding two independently-injected delegates would do the same job with a smaller interface. This example belongs in the guide precisely because it's the shape people reach for reflexively once they've learned the pattern, even where the family relationship is thin.
3. Document export — report-format families
A reporting module must emit a formatted document plus a matching thumbnail preview, consistently, across PDF and DOCX outputs.
// Reporting/IExportFactory.cs
public interface IExportFactory
{
IDocumentWriter CreateDocumentWriter();
IThumbnailRenderer CreateThumbnailRenderer();
}
public sealed class PdfExportFactory : IExportFactory
{
public IDocumentWriter CreateDocumentWriter() => new PdfDocumentWriter();
public IThumbnailRenderer CreateThumbnailRenderer() => new PdfThumbnailRenderer();
}
public sealed class ReportExportService(IExportFactory exportFactory)
{
public async Task<ExportedReport> ExportAsync(ReportModel model, CancellationToken ct)
{
var writer = exportFactory.CreateDocumentWriter();
var thumbnailer = exportFactory.CreateThumbnailRenderer();
var bytes = await writer.WriteAsync(model, ct);
var thumbnail = await thumbnailer.RenderAsync(bytes, ct);
return new ExportedReport(bytes, thumbnail);
}
}
Testing Code That Uses It
Abstract Factory is generally kind to tests: the client depends on an interface, so a fake factory returning fake products is the whole test double. The specific pain is the opposite direction — testing a concrete factory itself tends to duplicate the tests of every product it creates, unless you test only the wiring.
// Tests/CheckoutServiceTests.cs — faking the whole family via one factory
public class CheckoutServiceTests
{
[Fact]
public async Task ChargeAsync_uses_gateway_and_vault_from_the_same_factory()
{
var gateway = Substitute.For<IChargeGateway>();
var vault = Substitute.For<ITokenVault>();
vault.TokenizeAsync(Arg.Any<Card>(), Arg.Any<CancellationToken>())
.Returns(new Token("tok_123"));
gateway.ChargeAsync(Arg.Any<Token>(), Arg.Any<decimal>(), Arg.Any<CancellationToken>())
.Returns(ChargeResult.Success);
var factory = Substitute.For<IPaymentProviderFactory>();
factory.CreateChargeGateway().Returns(gateway);
factory.CreateTokenVault().Returns(vault);
var sut = new CheckoutService(factory);
var result = await sut.ChargeAsync(SampleOrder(), CancellationToken.None);
Assert.Equal(ChargeResult.Success, result);
await vault.Received(1).TokenizeAsync(Arg.Any<Card>(), Arg.Any<CancellationToken>());
}
}
// Tests/StripeProviderFactoryTests.cs — integration-level: test only the wiring
[Fact]
public void StripeProviderFactory_creates_a_matched_stripe_family()
{
var factory = new StripeProviderFactory();
var gateway = factory.CreateChargeGateway();
var vault = factory.CreateTokenVault();
Assert.IsType<StripeChargeGateway>(gateway);
Assert.IsType<StripeTokenVault>(vault);
// Deliberately NOT re-testing StripeChargeGateway's charging logic here --
// that belongs to StripeChargeGateway's own test class.
}
When To Use It — And When Not To
Use it when:
- Three or more products must be created together and swapped as a coherent unit (a UI kit, a regional compliance ruleset, a hardware driver bundle).
- The family choice is made once, early, and the resulting objects flow through a large surface of unrelated code that shouldn't need to know the choice was made.
- You need to guarantee — structurally, not by convention — that mismatched family members can never be paired.
Don't use it when:
- You have exactly two implementations and no third is plausible — an
ifor a single injected interface is clearer. - The "family" has never actually changed in the life of the codebase; you're paying the interface-explosion tax for a variation point that's theoretical.
- A
Func<Order, decimal>-shaped delegate parameter would do the whole job — don't wrap one function in an interface namedIPricingStrategyFactory. - Your DI container already owns the object graph and keyed services would express the same intent with less ceremony (§6, §12).
- The indirection will be read primarily by people who won't have this document open next to them — a plain
switchin one obvious place can be more honest than an abstraction three files deep.
Pros and Cons, Honestly
| Pros | Cons |
|---|---|
| Guarantees family consistency structurally, not by convention | Adding one product means editing every concrete factory's interface implementation |
| Isolates concrete-type knowledge to the composition root | An extra layer of interfaces and classes for what's sometimes just "pick an implementation" |
| Client code is trivially testable via a fake factory | Concrete factories themselves are awkward to unit test without duplicating product tests |
| Swapping a family is a one-line change at the composition root | Often reimplements what a DI container's keyed services already do natively |
The con list is not shorter than the pros here on purpose — the interface-growth cost is real and unavoidable for the classic form; every genuine advantage above has a matching modern alternative that captures much of it more cheaply.
Contested trade-off: Steven van Deursen and Mark Seemann's Dependency Injection Principles, Practices, and Patterns argues Abstract Factory is frequently overused in DI-based codebases specifically because service abstractions shouldn't expose other service abstractions — a factory interface forces every consumer to depend on both the factory and the products, when the products alone would do. The counter-argument: in genuinely cross-cutting, multi-product families (regional compliance rule sets spanning five or six coordinated services), a structural guarantee of consistency is worth more than the extra dependency, because a keyed-service misconfiguration failure mode — the wrong provider silently paired with the wrong vault — is a production incident, not a compile error. Competent people land differently on where that line sits.
Common Mistakes and Anti-Patterns
Mistake 1 — bypassing the factory for "just one" product
// ❌ Wrong — a Windows type sneaks in directly, breaking the family guarantee
public void RenderExtra(IGuiFactory factory)
{
var button = factory.CreateButton();
var tooltip = new WindowsTooltip(); // <-- not from the factory
button.Draw();
tooltip.Draw();
}
// ✅ Right — the tooltip is added to the factory's contract, or the family
// genuinely doesn't need one and the guide's checklist says so explicitly.
public interface IGuiFactory
{
IButton CreateButton();
ICheckbox CreateCheckbox();
ITooltip CreateTooltip();
}
The rationale: the moment one product bypasses the factory, the pattern's structural guarantee is gone and becomes a convention again — exactly the failure mode from §2's "before" code.
Mistake 2 — a factory interface that grows unrelated responsibilities
// ❌ Wrong — CreateLogger has nothing to do with the UI family
public interface IGuiFactory
{
IButton CreateButton();
ICheckbox CreateCheckbox();
ILogger CreateLogger(); // <-- varies independently, doesn't belong here
}
// ✅ Right — logger is an ordinary injected dependency, unrelated to the family
public sealed class DialogRenderer(IGuiFactory guiFactory, ILogger<DialogRenderer> logger)
{
// ...
}
Mistake 3 — the subtle one: a "stateless" family factory that isn't
// ❌ Wrong — compiles, passes tests, breaks under concurrent requests months later
public sealed class TenantThemeFactory : IGuiFactory
{
private string _lastTenantId = ""; // <-- mutable field, registered as Singleton
public IButton CreateButton() => new TenantButton(_lastTenantId);
public void SetTenant(string tenantId) => _lastTenantId = tenantId;
}
// ✅ Right — the tenant id is a parameter, not shared mutable state
public sealed class TenantThemeFactory : IGuiFactory
{
public IButton CreateButton(string tenantId) => new TenantButton(tenantId);
}
// registered as Singleton safely, because it now holds no per-request state
The bug: registered as a DI singleton, _lastTenantId is shared across every concurrent request. Two requests for different tenants racing against each other silently cross-contaminate — it compiles, the single-threaded test suite passes, and it fails only under real concurrent load.
Refactoring Path — Introducing It Into Existing Code
- Extract product interfaces from the existing concrete
WindowsButton/MacButtontypes — this alone is shippable and touches nothing else. - Introduce
IGuiFactorywith one creation method per product already identified. - Write one concrete factory per existing switch branch — largely mechanical, since the branch bodies already exist.
- Replace exactly one call site's switch with a factory call, leaving the rest untouched and the app fully working.
- Repeat, one call site per commit — each step is independently reviewable and revertible.
- Delete the original switch only once no call site references it — grep for the enum name first.
The seam to cut first is the constructor calls, not the enum — cutting the enum too early leaves every intermediate commit in a broken state. Keep the old UiTheme enum alive through the whole migration; it becomes the factory-selection key at the very end.
ADR template — Introducing Abstract Factory for [family name]
Context: [what varies together, why a switch/if-chain became unmanageable]
Decision: introduce I[Family]Factory with methods [list]; register concrete factories at the composition root keyed by [selection criterion].
Consequences: adding a new product requires updating every concrete factory (accepted cost); adding a new family variant requires only a new factory class and one registration line.
Alternatives considered: keyed DI services (rejected because [reason]); plain Func<T> parameters (rejected because [reason]).
Reference Checklist
- Every product the client touches comes from the factory — no direct
newof a concrete family member anywhere outside a concrete factory class. - The factory interface contains only creation methods — no unrelated responsibilities (§14, Mistake 2).
- Concrete factories and products are
sealedunless there's a specific reason to allow inheritance. - No mutable per-call state lives on a factory registered with a longer lifetime than that state's actual scope (§14, Mistake 3).
- Before adding a factory interface, keyed DI services and
Func<T>parameters have both been considered and rejected for a stated reason. - Concrete-factory tests verify wiring only; product behaviour is tested in the product's own test class.
- The composition root is the only place a family variant is chosen by branching on configuration.
Sources
Primary
- Gamma, Helm, Johnson, Vlissides — Design Patterns: Elements of Reusable Object-Oriented Software (1994), the Abstract Factory chapter.
Analysis and critique
- van Deursen & Seemann, "Abuse of Abstract Factories," Manning / Dependency Injection Principles, Practices, and Patterns
- Steven van Deursen, "Abstract Factories are a Code Smell," .NET Junkie
- "Keyed Services in .NET Core 8: The Death of the Factory Pattern?"
.NET documentation and API references
- Microsoft Learn —
ILoggerFactoryand logging providers in ASP.NET Core - Microsoft Learn —
System.Data.Common.DbProviderFactory - Microsoft Learn — keyed services in
Microsoft.Extensions.DependencyInjection(.NET 8+) - Microsoft — .NET 10 release notes and C# 14 language reference