Skip to content

6.8 — Factory Registrations and Open Generics

← Roadmap · Section: 6. Dependency Injection Prev: 6.7 Multiple implementations · Next: 6.9 Injection styles

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

Two registration techniques for when the simple AddScoped<IFoo, Foo>() form is not enough.

  • A factory registration gives you a lambda that builds the object, so construction can involve logic — reading config, choosing between implementations, passing a computed value.
  • An open generic registration registers IRepository<> once and serves IRepository<Order>, IRepository<Customer> and every other closed version.
  • Both are ways of saying "I cannot express this with a type pair alone".

Definitions

Term What it is What it means
Factory registration a registration style You supply a lambda sp => new Thing(...) that builds the instance.
IServiceProvider sp the lambda's parameter The container, so the factory can resolve other services.
Open generic a generic type with no arguments IRepository<> — written with empty angle brackets.
Closed generic a generic type with arguments IRepository<Order>.
typeof(IRepository<>) the syntax How you refer to an open generic in C#.
Generic type argument the filled-in type The Order in IRepository<Order>.
ActivatorUtilities a static class Creates an object with DI-resolved dependencies plus extra arguments you supply.
Decorator a design pattern Wrapping a service in another that adds behaviour. See 22.4.
Lazy resolution a behaviour The factory runs when the service is first requested, not at registration.

The concept

When a type pair is not enough

Most registrations are simple: "when someone asks for IFoo, give them Foo".

builder.Services.AddScoped<IOrderService, OrderService>();

The container inspects OrderService's constructor and resolves everything itself. That covers the large majority of cases.

Two situations break it:

Construction needs a decision. Which storage provider? What connection string? A value from configuration that is not itself a service.

The type is generic and you do not want to register every version. IRepository<Order>, IRepository<Customer>, IRepository<Invoice> — twenty entities means twenty near-identical lines, and one more every time someone adds an entity.

Factory registrations solve the first; open generics solve the second.


How it works

The simple version — a factory

builder.Services.AddSingleton<IStorageProvider>(sp =>
{
    var config = sp.GetRequiredService<IConfiguration>();

    return config["Storage:Provider"] switch
    {
        "azure" => new AzureBlobStorage(config["Storage:ConnectionString"]!),
        "s3"    => new S3Storage(config["Storage:Bucket"]!),
        _       => new LocalFileStorage(config["Storage:Path"]!)
    };
});

The lambda receives the IServiceProvider, so it can resolve anything already registered.

⚠️ The factory runs lazily — on first resolution, not at registration. So a configuration error inside it does not surface at startup; it surfaces on the first request that needs the service, potentially much later and in a confusing place.

If the failure should be loud and early, either validate at startup or enable ValidateOnBuild (6.2).

⚠️ Which provider does the factory get?

This catches people out. The sp passed to the factory is the provider for the scope the service is being created in:

builder.Services.AddScoped<IThing>(sp =>
{
    var db = sp.GetRequiredService<AppDbContext>();      // ✓ the REQUEST's DbContext
    return new Thing(db);
});

For a scoped registration that is the request scope, so resolving other scoped services is correct.

For a singleton registration it is the root provider — so resolving a scoped service there is a captive dependency (6.4):

// ✗ WRONG — a singleton factory resolving a scoped service
builder.Services.AddSingleton<IThing>(sp =>
{
    var db = sp.GetRequiredService<AppDbContext>();      // ⚠️ captured forever
    return new Thing(db);
});

The lifetime rules apply inside factories exactly as they do in constructors.

Passing values a class needs

A common case — a constructor parameter that is not a service:

public class RetryPolicy(IHttpClientFactory factory, int maxAttempts) { }
builder.Services.AddSingleton(sp => new RetryPolicy(
    sp.GetRequiredService<IHttpClientFactory>(),
    maxAttempts: 3));

⚠️ But for anything configurable, use the options pattern instead. Hard-coding 3 in Program.cs means it cannot be changed per environment:

builder.Services.Configure<RetryOptions>(builder.Configuration.GetSection("Retry"));
builder.Services.AddSingleton<RetryPolicy>();     // takes IOptions<RetryOptions>

See 7.6.

ActivatorUtilities is the middle ground when you need DI plus runtime arguments:

var policy = ActivatorUtilities.CreateInstance<RetryPolicy>(provider, maxAttempts);
// Resolves IHttpClientFactory from DI, takes maxAttempts from you

How it actually works — open generics

Registering a generic repository for every entity is unworkable:

// ✗ One line per entity, forever
builder.Services.AddScoped<IRepository<Order>, EfRepository<Order>>();
builder.Services.AddScoped<IRepository<Customer>, EfRepository<Customer>>();
builder.Services.AddScoped<IRepository<Invoice>, EfRepository<Invoice>>();

An open generic registration covers all of them:

builder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));

Note the syntax: typeof(IRepository<>) with empty angle brackets. That is how C# refers to a generic type with its arguments unfilled.

Now anything can inject any closed version:

public class OrderService(IRepository<Order> orders) { }
public class CustomerService(IRepository<Customer> customers) { }

The container builds EfRepository<Order> when asked for IRepository<Order>. It substitutes the type argument automatically.

⚠️ The generic parameters must line up. IRepository<T> and EfRepository<T> need the same arity and compatible constraints, or you get a runtime error at resolution rather than a compile error:

public interface IRepository<T> where T : class, IEntity { }
public class EfRepository<T>(AppDbContext db) : IRepository<T> where T : class, IEntity { }

See 1.10.

This is how the framework registers ILogger<T>, which is why you can inject ILogger<AnyClassYouWrite> without registering anything.

The deeper detail — decoration with factories

Factories let you wrap a service in another that adds behaviour:

builder.Services.AddScoped<OrderRepository>();          // the real one, as itself

builder.Services.AddScoped<IOrderRepository>(sp =>
{
    var inner = sp.GetRequiredService<OrderRepository>();
    var cache = sp.GetRequiredService<IMemoryCache>();
    return new CachingOrderRepository(inner, cache);    // wrap it
});

Consumers inject IOrderRepository and get caching transparently.

⚠️ Register the inner one as its concrete type, not as the interface. Registering both as IOrderRepository and resolving the interface inside the factory would make the decorator wrap itself and recurse forever.

The library Scrutor makes this much cleaner:

builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.Decorate<IOrderRepository, CachingOrderRepository>();

See 6.11.


Code

A realistic set showing both techniques where they genuinely earn their place:

// ── Open generic: one line covers every entity ──
builder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));

// ── Factory: the implementation depends on configuration ──
builder.Services.AddSingleton<IFeatureFlags>(sp =>
{
    var config = sp.GetRequiredService<IConfiguration>();
    var logger = sp.GetRequiredService<ILogger<IFeatureFlags>>();

    var endpoint = config["FeatureFlags:Endpoint"];

    if (string.IsNullOrEmpty(endpoint))
    {
        logger.LogWarning("No feature flag endpoint configured — using local defaults");
        return new LocalFeatureFlags(config.GetSection("FeatureFlags:Defaults"));
    }

    return new RemoteFeatureFlags(
        sp.GetRequiredService<IHttpClientFactory>(),
        endpoint);
});

// ── Factory: decoration ──
builder.Services.AddScoped<PriceCalculator>();                 // concrete
builder.Services.AddScoped<IPriceCalculator>(sp =>
    new LoggingPriceCalculator(
        sp.GetRequiredService<PriceCalculator>(),
        sp.GetRequiredService<ILogger<LoggingPriceCalculator>>()));

And the generic repository that the open registration serves:

public interface IRepository<T> where T : class, IEntity
{
    Task<T?> GetAsync(Guid id, CancellationToken ct);
    Task<IReadOnlyList<T>> ListAsync(CancellationToken ct);
    Task AddAsync(T entity, CancellationToken ct);
}

public class EfRepository<T>(AppDbContext db) : IRepository<T>
    where T : class, IEntity
{
    public Task<T?> GetAsync(Guid id, CancellationToken ct)
        => db.Set<T>().FirstOrDefaultAsync(e => e.Id == id, ct);

    public async Task<IReadOnlyList<T>> ListAsync(CancellationToken ct)
        => await db.Set<T>().AsNoTracking().ToListAsync(ct);

    public async Task AddAsync(T entity, CancellationToken ct)
        => await db.Set<T>().AddAsync(entity, ct);
}

⚠️ Whether a generic repository is a good idea at all is a separate argument — EF Core's DbSet<T> already is one, and wrapping it often loses capability without gaining much. See 13.19.


Interview questions

Q: When would you use a factory registration?

When construction needs logic rather than just picking a type — choosing an implementation based on configuration, passing a computed value, or wrapping one service in another. The lambda receives the IServiceProvider, so it can resolve whatever else it needs. Two things to watch: the factory runs lazily on first resolution rather than at startup, so a configuration error surfaces late; and the lifetime rules still apply inside it, so a singleton factory resolving a scoped service is a captive dependency exactly as it would be in a constructor.

Q: What is an open generic registration?

Registering a generic type without its type arguments filled in, using typeof(IRepository<>) with empty angle brackets. One registration then serves every closed version — IRepository<Order>, IRepository<Customer> and so on — with the container substituting the type argument when it builds the instance. It avoids one registration line per entity, and it is exactly how the framework registers ILogger<T>, which is why you can inject a logger for any class without registering anything.

Q: What provider does a factory lambda receive?

The one for the scope the service is being created in. For a scoped registration that is the request scope, so resolving other scoped services from it is correct. For a singleton registration it is the root provider, so resolving a scoped service there captures it for the application's lifetime — the same captive dependency problem you would get from constructor injection. The lifetime rules do not relax inside factories.

Q: How would you add caching to an existing repository without changing it?

Decoration. Register the real repository as its concrete type, then register the interface with a factory that resolves the concrete one and wraps it in a caching implementation. Consumers keep injecting the interface and get caching transparently. The thing to be careful about is registering the inner service as its concrete type rather than the interface — otherwise the decorator resolves the interface, finds itself, and recurses infinitely. Scrutor's Decorate method makes this a single line and handles that correctly.


Traps ⚠️

  • Factories run lazily, so errors inside them surface on first use rather than at startup.
  • A singleton factory resolving a scoped service is a captive dependency.
  • A decorator registered as the interface it resolves wraps itself and recurses forever.
  • Open generic arity and constraints must match, or resolution fails at runtime rather than compile time.
  • typeof(IRepository<>) needs empty angle brackets. typeof(IRepository) will not compile for a generic type.
  • Hard-coding values in a factory makes them unconfigurable. Use IOptions<T>.
  • Factories bypass constructor inspection, so ValidateOnBuild cannot verify what happens inside them.


Sources