📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is the difference between a simple factory, the Factory Method pattern and the Abstract Factory pattern? Give a .NET framework example of each and explain when DI makes a hand-written factory unnecessary.

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.

Intermediate Theory Intermediate abstract-factory ado-net dependency-injection design-patterns factory-method

🎯 Key points

  • Simple factory: one method with a switch that returns an implementation; not a GoF pattern, fine for small closed sets, but adding a type edits the switch (violates Open/Closed)
  • Factory Method: a base class defines a virtual/abstract creation method and subclasses decide the concrete type (DbConnection.CreateCommand calls protected abstract CreateDbCommand)
  • Abstract Factory: an interface for creating a family of related objects that must match (DbProviderFactory: CreateConnection, CreateCommand, CreateParameter), so you can't mix providers
  • IHttpClientFactory.CreateClient(name) creates configured clients and pools HttpMessageHandlers (2-minute default lifetime); ILoggerFactory.CreateLogger(category) creates loggers backed by providers
  • DbDataSource (.NET 7+, current in .NET 10) is the modern abstract-factory-style entry point for ADO.NET providers (e.g. NpgsqlDataSource, registered with AddNpgsqlDataSource)
  • A DI container is a general-purpose factory: AddScoped<IFoo, Foo>(), factory delegates (sp => new Foo(...)), keyed services (.NET 8+) and ActivatorUtilities replace most hand-written factories
  • Write a factory when creation needs run-time data the container doesn't have (tenant, provider, region) or many short-lived instances on demand; it is the Dependency Inversion seam for creation
  • A factory that takes IServiceProvider and calls GetService from business code is a service locator; keep container access at the composition root

⏱ 30-second answer

  • A simple factory is one method, usually a switch, that returns the right implementation. It isn't a GoF pattern, but it's fine for a small closed set.
  • Factory Method lets a base class define the creation step while subclasses choose the type. In .NET, DbConnection.CreateCommand() calls the protected abstract CreateDbCommand(), so SqlConnection returns a SqlCommand.
  • Abstract Factory is an interface that creates a family of related objects that must match. 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"All three move the new out of the code that uses the object, but at different scales. A simple factory is just a method, usually static with a switch, 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 abstract CreateDbCommand(), so a SqlConnection hands you a SqlCommand and an NpgsqlConnection hands you an NpgsqlCommand, 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. DbProviderFactory gives you a connection, command, parameter and data adapter for one provider, so you can't accidentally mix a SqlParameter with an Npgsql command. In .NET 7 and later, DbDataSource plays that role for providers like Npgsql.

Other framework factories I use every day are IHttpClientFactory, which creates named or typed clients and pools the HttpMessageHandlers underneath with a two-minute default lifetime, and ILoggerFactory, 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 like sp => new Foo(options.Value.Url), or a keyed service covers most of what people used to write FooFactory classes for.

The mistake I see is a factory that takes IServiceProvider and calls GetService from 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."


Side by side

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

Framework factories worth knowing

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

When to write a factory vs use DI

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

Production example

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.

πŸ” What the interviewer is checking

Checks that the candidate distinguishes the three factory variants precisely and knows how DI changes their use.

Green flags

  • Explains Factory Method as subclass-decides and Abstract Factory as families.
  • Gives real framework examples (DbConnection.CreateCommand, DbProviderFactory, IHttpClientFactory).
  • Knows when a factory is needed versus a DI registration.
  • Distinguishes a typed factory from a service locator.

Red flags

  • Uses the three names interchangeably.
  • Writes factories that only wrap new.
  • Passes IServiceProvider around as "a factory".

πŸ“š Learn in depth

1. Structures

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.

2. Factory Method in the BCL

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.

3. Abstract Factory in ADO.NET

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.

4. The DI container as a factory

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

5. Service locator vs factory

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.

6. Costs

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.

Try it yourself

  1. Write code that uses only DbProviderFactory to run SELECT 1 against SQLite and SQL Server by changing one registration.
  2. Find CreateDbCommand in the Microsoft.Data.SqlClient source and follow it to SqlCommand.
  3. Replace a hand-written FooFactory that just calls new Foo(dep1, dep2) with a DI registration and delete the factory.
  4. Use ActivatorUtilities.CreateInstance to create a class that needs both a service and a run-time tenantId.

πŸ’» Code

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>();

⚠ Common mistakes

  • Mistake: Calling every method that returns an object a "Factory Method". Why it is wrong: GoF Factory Method is specifically a creation step overridden by subclasses; a static switch is a simple factory. Instead: Use the precise name; interviewers notice.
  • Mistake: Writing 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.
  • Mistake: Passing 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.
  • Mistake: Mixing products from different families (an 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.
  • Mistake: Creating 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.
  • Mistake: An Abstract Factory with one concrete factory "in case we switch databases". Why it is wrong: Speculative generality; every call pays the indirection and nobody ever switches. Instead: Introduce it when a second family genuinely exists.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate describes Factory Method with an abstract base class Why: Checks abstract classes and Template Method, which Factory Method relies on
    How to answer

    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.

  2. When: Candidate says the container replaces hand-written factories Why: Checks dependency inversion versus the mechanics of DI
    How to answer

    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.

  3. When: Candidate says a factory is needed when the choice depends on run-time data Why: Checks run-time implementation selection with keyed services without a service locator
    How to answer

    This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:

    • Keyed services (.NET 8+): 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.
    • Typed resolver over keyed services: 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.

↩ Usually asked after

More in Creational Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me