Simple factory vs GoF Factory Method (subclass decides, DbConnection.CreateCommand) vs Abstract Factory (families of related objects, DbProviderFactory, DbDataSource), IHttpClientFactory and ILoggerFactory, and when DI factory delegates replace them.
switch, that returns the right implementation. It isn't a GoF pattern, but it's fine for a small closed set.DbConnection.CreateCommand() calls the protected abstract CreateDbCommand(), so SqlConnection returns a SqlCommand.DbProviderFactory creates the connection, command and parameter for one provider, and DbDataSource (.NET 7+) is the modern equivalent.In an ASP.NET Core app the DI container is the factory: registrations, factory delegates and keyed services cover most cases. A hand-written factory still pays off when creation needs run-time data the container doesn't have. The trap is that one taking IServiceProvider everywhere becomes a service locator.
"All three move the
newout of the code that uses the object, but at different scales. A simple factory is just a method, usually static with aswitch, that returns the right implementation for an input. It isn't one of the GoF patterns, but it's often all you need. Factory Method is about inheritance: a base class defines an overridable creation method and uses it inside its own logic, and subclasses decide the concrete type. ADO.NET is the textbook case.DbConnection.CreateCommand()calls a protected abstractCreateDbCommand(), so aSqlConnectionhands you aSqlCommandand anNpgsqlConnectionhands you anNpgsqlCommand, without the base class knowing either. Abstract Factory goes one level up: an interface that creates a whole family of objects that have to match.DbProviderFactorygives you a connection, command, parameter and data adapter for one provider, so you can't accidentally mix aSqlParameterwith an Npgsql command. In .NET 7 and later,DbDataSourceplays that role for providers like Npgsql.Other framework factories I use every day are
IHttpClientFactory, which creates named or typed clients and pools theHttpMessageHandlers underneath with a two-minute default lifetime, andILoggerFactory, which creates category loggers backed by whatever providers are registered. In application code, though, the DI container is a general-purpose factory. A registration, a factory delegate likesp => new Foo(options.Value.Url), or a keyed service covers most of what people used to writeFooFactoryclasses for.The mistake I see is a factory that takes
IServiceProviderand callsGetServicefrom business code. That's a service locator: dependencies become invisible and failures move from startup to run time. I write a factory when creation needs data only known at run time; otherwise I let the container create things."
| Simple factory | Factory Method | Abstract Factory | |
|---|---|---|---|
| Mechanism | A method with a switch |
A virtual creation method overridden by subclasses | An interface with several creation methods |
| Creates | One product | One product | A family of related products |
| Varies by | Input parameter | Subclass | Concrete factory instance |
| .NET example | Encoding.GetEncoding(name) |
DbConnection.CreateCommand() β CreateDbCommand() |
DbProviderFactory, DbDataSource |
| Open/Closed | Edit the switch to add a type | Add a subclass | Add a factory implementation |
| Factory | Creates | Why it exists |
|---|---|---|
IHttpClientFactory |
HttpClient (named/typed) |
Pools and rotates handlers to avoid socket exhaustion and stale DNS |
ILoggerFactory |
ILogger per category |
Fans one logger out to all ILoggerProviders |
IDbContextFactory<T> |
DbContext |
Short-lived contexts in singletons, Blazor Server, parallel work |
ObjectPoolProvider |
ObjectPool<T> |
Pool creation with a policy |
ActivatorUtilities.CreateInstance |
Any type | Mix DI services with run-time arguments |
| Use DI registration | Write a factory |
|---|---|
| Implementation is known at startup | Implementation depends on request data (tenant, provider, region) |
| Constructor needs only services and options | Constructor needs a run-time value plus services |
| One instance per lifetime is fine | Caller needs many short-lived instances on demand |
A reporting service that supported both SQL Server and PostgreSQL customers used if (isPostgres) checks in 40 places to create connections and parameters, and twice shipped bugs where a SqlParameter was added to an NpgsqlCommand. Replacing those checks with an injected DbProviderFactory chosen once at startup per tenant removed the branches and that class of bug entirely.
Checks that the candidate distinguishes the three factory variants precisely and knows how DI changes their use.
Green flags
DbConnection.CreateCommand, DbProviderFactory, IHttpClientFactory).Red flags
new.IServiceProvider around as "a factory".Factory Method
Creator (abstract) Product (abstract)
+ Operation() { p = Create(); ... } uses ββΆ β²
# abstract Create(): Product β
β² ConcreteProduct
β β²
ConcreteCreator βββββββββ creates βββββββββββββββ
# override Create() => new ConcreteProduct()
Abstract Factory
Β«abstractΒ» DbProviderFactory
+ CreateConnection() + CreateCommand() + CreateParameter()
β² β²
SqlClientFactory NpgsqlFactory
β SqlConnection, SqlCommand, β NpgsqlConnection, NpgsqlCommand,
SqlParameter NpgsqlParameter
The key property of Abstract Factory is consistency: everything from one factory belongs together.
public abstract class DbConnection
{
public DbCommand CreateCommand() => CreateDbCommand(); // public, non-virtual
protected abstract DbCommand CreateDbCommand(); // the factory method
}
The public method can add common behaviour later without breaking providers. That non-virtual-public / protected-virtual split is also the Template Method pattern; the two often appear together.
DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance);
DbProviderFactory factory = DbProviderFactories.GetFactory("Microsoft.Data.SqlClient");
await using DbConnection conn = factory.CreateConnection()!;
In .NET Framework factories were registered in machine.config. In modern .NET you register them in code. DbDataSource (.NET 7) wraps connection-string handling and connection creation, and providers like Npgsql expose NpgsqlDataSource as the recommended entry point, often registered in DI with AddNpgsqlDataSource.
| Need | DI feature |
|---|---|
| Choose implementation at startup | if (config.UseFake) services.AddScoped<IX, Fake>() else ... |
| Construct with options | Factory delegate: services.AddSingleton<IX>(sp => new X(sp.GetRequiredService<IOptions<XOptions>>().Value)) |
| Several implementations by name | Keyed services (.NET 8): AddKeyedScoped<IX, A>("a") |
| Mix services and run-time args | ActivatorUtilities.CreateInstance<X>(sp, runtimeArg) |
| Create on demand | Inject Func<IX> registered as a factory, or a dedicated factory interface |
A factory has a narrow, typed interface (IPaymentGatewayFactory.Create(provider)). A service locator exposes the whole container (IServiceProvider) to business code. The first is a design choice with a testable seam; the second hides dependencies. A factory implementation may use IServiceProvider internally if it lives in the composition root, because the dependency on the container stays in one place.
A factory call is one extra virtual or interface call, which is negligible. Abstract Factory adds one interface and one class per family. The main cost is conceptual: readers must find which factory is registered to know which type they get.
DbProviderFactory to run SELECT 1 against SQLite and SQL Server by changing one registration.CreateDbCommand in the Microsoft.Data.SqlClient source and follow it to SqlCommand.FooFactory that just calls new Foo(dep1, dep2) with a DI registration and delete the factory.ActivatorUtilities.CreateInstance to create a class that needs both a service and a run-time tenantId.Factory Method, Abstract Factory via DbProviderFactory, and the DI version of a factory:
namespace Factories;
using System.Data.Common;
// Factory Method: base class owns the algorithm, subclasses choose the product
public abstract class ReportExporter
{
public async Task ExportAsync(Report report, Stream output, CancellationToken ct)
{
IReportWriter writer = CreateWriter(output); // the factory method
await writer.WriteHeaderAsync(report, ct);
foreach (ReportRow row in report.Rows)
await writer.WriteRowAsync(row, ct);
}
protected abstract IReportWriter CreateWriter(Stream output);
}
public sealed class CsvExporter : ReportExporter
{
protected override IReportWriter CreateWriter(Stream output) => new CsvReportWriter(output);
}
// Abstract Factory: everything from one factory matches the same provider
public sealed class OrderQueries(DbProviderFactory factory, string connectionString)
{
public async Task<int> CountAsync(string status, CancellationToken ct)
{
await using DbConnection conn = factory.CreateConnection()!;
conn.ConnectionString = connectionString;
await conn.OpenAsync(ct);
await using DbCommand cmd = conn.CreateCommand(); // Factory Method on DbConnection
cmd.CommandText = "SELECT COUNT(*) FROM Orders WHERE Status = @status";
DbParameter p = factory.CreateParameter()!; // same family, so it matches the command
p.ParameterName = "@status";
p.Value = status;
cmd.Parameters.Add(p);
return Convert.ToInt32(await cmd.ExecuteScalarAsync(ct));
}
}
// Program.cs: the container is the factory; no FooFactory class needed
builder.Services.AddSingleton<DbProviderFactory>(Microsoft.Data.SqlClient.SqlClientFactory.Instance);
builder.Services.AddScoped(sp => new OrderQueries(
sp.GetRequiredService<DbProviderFactory>(),
builder.Configuration.GetConnectionString("Orders")!)); // factory delegate supplies config
builder.Services.AddScoped<ReportExporter, CsvExporter>();
FooFactory.Create() that just calls new Foo(a, b) with injected services. Why it is wrong: It duplicates what the container does and adds a type to maintain. Instead: Register Foo and inject it, or use a factory delegate.IServiceProvider into domain or application services to "create" things. Why it is wrong: That is a service locator; dependencies are hidden and missing registrations fail at run time. Instead: Inject a narrow typed factory, keyed services, or the dependency itself.SqlParameter on an NpgsqlCommand). Why it is wrong: It throws InvalidCastException at run time. Instead: Create all related objects from the same DbProviderFactory or DbDataSource.new HttpClient() inside a home-made factory. Why it is wrong: Each client with its own handler opens new sockets; under load you get socket exhaustion. Instead: Use IHttpClientFactory or one long-lived HttpClient with PooledConnectionLifetime.In modern .NET the question is rarely "which factory pattern?" and usually "does this need a factory at all, or is it a DI registration?" The container already handles construction, lifetimes and disposal. I write a dedicated factory interface only when creation needs run-time input such as a tenant, a provider name or a region, or when a caller needs many short-lived instances. Even then the implementation lives at the composition root.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Plain DI registration | Type known at startup | None | Run-time choice |
| Factory delegate | Construction needs config or a computed value | A lambda | Complex logic (move to a class) |
| Keyed services (.NET 8+) | Fixed set of named implementations | Keys are strings/objects, typos fail at run time | Open-ended or data-driven sets |
| Typed factory interface | Run-time data decides, or many instances on demand | One interface and class | When DI alone covers it |
| Abstract Factory | A family of products must stay consistent | One class per family | Only one family exists |
The check I use: if deleting the factory and registering the product directly compiles and passes the tests, the factory was ceremony.
An abstract class is a base class that cannot be instantiated and may declare abstract members with no body, which every non-abstract derived class must override. Unlike an interface it can hold instance fields, constructors and fully implemented members, so it is the place for shared state and a shared algorithm. The classic use is the template method pattern: a public non-virtual method defines the steps and calls protected abstract or protected virtual hooks. Constructors should be protected. A class can derive from only one abstract class. Adding a new virtual member with a body is non-breaking, but adding a new abstract member breaks every derived class.
DIP says high-level policy should not depend on low-level details; both should depend on abstractions, and the abstraction belongs to the high-level side. For example, the domain or application layer defines IPaymentGateway, and the infrastructure project implements it with Stripe; the arrow of source dependency points inwards. Dependency injection is a technique for supplying those implementations (constructor injection), and the .NET DI container is a tool that automates it. You can use a container without inverting anything (if interfaces live next to their implementations in infrastructure), and you can invert dependencies without a container.
This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:
AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe"), then inject with [FromKeyedServices("stripe")]. This only works when the key is known at compile time.IEnumerable<IPaymentGateway> resolver: each gateway exposes a Provider key, and a resolver builds a FrozenDictionary from them. There's no container access, but every gateway is constructed.IPaymentGatewayResolver.Resolve(provider) calls GetRequiredKeyedService inside the composition root. It builds only the gateway you need.To avoid a service locator, business code depends on a narrow typed resolver, never on IServiceProvider. Map unknown keys to a domain error, and validate the configured keys at startup.
Last updated 18 Nov 2026.