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

📚 Interview question

Code review: an OrderService constructor takes 12 injected dependencies (repositories, email, SMS, PDF, tax, discount, audit, cache, logger and more), and its methods also new up a TaxCalculator and an HttpClient. What problems do you see, ranked by severity, and how would you refactor it?

Reviews a class with constructor over-injection and hidden new-ed dependencies: SRP violations, socket exhaustion from new HttpClient, untestable collaborators, and refactoring into focused handlers, domain events and facade services.

Mid-Level CodeReview Intermediate code-review constructor-over-injection dependency-injection httpclient refactoring single-responsibility

🎯 Key points

  • new HttpClient() per call risks socket exhaustion (TIME_WAIT), extra TLS handshakes per request and stale DNS: use IHttpClientFactory or a typed client
  • new TaxCalculator() inside methods is a hidden dependency: untestable and bypasses configuration
  • 12 constructor parameters plus hidden new calls mean the class breaks SRP: tight coupling, large test setup, every change risks unrelated behaviour
  • Group by use case: split into focused handlers (PlaceOrder, CancelOrder) that each need 3-4 dependencies
  • Move side effects (email, SMS, PDF, audit) behind a domain event or outbox handler
  • Introduce a facade only for a cohesive group (INotificationService), not as a bag of services
  • Don't hide the smell with property injection, IServiceProvider or a 'dependencies' parameter object
  • Ranked: resource leak first, then correctness and testability, then design

⏱ 30-second answer

The 12-parameter constructor is a symptom: the class has several responsibilities (placing, cancelling, notifying, invoicing, auditing). The new calls are the bugs.

  1. new HttpClient() in a method: socket exhaustion under load and stale DNS. Use IHttpClientFactory or a typed client.
  2. new TaxCalculator(): a hidden dependency that can't be faked or configured. Inject it.
  3. Over-injection: split by use case into focused handlers with 3-4 dependencies each, move side effects (email, SMS, PDF, audit) into domain event handlers, and introduce a facade only for a genuinely cohesive group like notifications.

The trade-off: more, smaller classes, in exchange for code where each class can be understood and tested on its own.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd rank the findings by how much damage they do. The worst is new HttpClient() inside a method: every call opens new connections and leaves sockets in TIME_WAIT, so under load you get socket exhaustion, and if you 'fix' it with a static client you stop seeing DNS changes. That gets fixed with IHttpClientFactory or a typed client before anything else. Next is new TaxCalculator(): a hidden dependency, so tax rules can't be faked in tests or configured per environment, and nobody reading the constructor knows the class does tax.

Then the twelve constructor parameters. That's not a DI problem, it's DI showing me a design problem: the class places orders, cancels them, sends email and SMS, renders PDFs and writes audit records. For example, at [company] we had [a similar service with N dependencies], and I [split it into per-use-case handlers and moved notifications behind a domain event], which [took the largest class from N to M dependencies and cut the test setup from X lines to Y]. My refactor is: one handler per use case, PlaceOrderHandler, CancelOrderHandler, each needing three or four things. Side effects that happen after the order is placed go into handlers for an OrderPlaced event, ideally via an outbox so a failing SMS doesn't roll back an order. If email, SMS and push really belong together, a small ICustomerNotifier facade is fine.

The mistake I see is hiding the smell instead of fixing it: property injection, a ServiceDependencies parameter object holding all twelve, or injecting IServiceProvider. All of those keep the coupling and just make it harder to see."


Code under review

public class OrderService(
    IOrderRepository orders, ICustomerRepository customers, IProductRepository products,
    IEmailSender email, ISmsSender sms, IPdfRenderer pdf, IDiscountService discounts,
    IAuditLog audit, IMemoryCache cache, IInventoryService inventory,
    IOptions<OrderOptions> options, ILogger<OrderService> logger)         // 3: 12 dependencies
{
    public async Task<int> PlaceAsync(PlaceOrderRequest request)
    {
        var tax = new TaxCalculator();                                    // 2: hidden dependency
        var total = tax.Apply(discounts.Apply(request.Lines));
        var id = await orders.AddAsync(request, total);

        using var http = new HttpClient();                                // 1: socket exhaustion
        await http.PostAsJsonAsync("https://warehouse.example/api/reserve", request);

        await email.SendAsync(request.Email, "Order placed");             // 4: side effects inline
        await sms.SendAsync(request.Phone, "Order placed");
        await pdf.RenderInvoiceAsync(id);
        await audit.WriteAsync($"Order {id} placed");
        return id;
    }

    public Task CancelAsync(int id) { /* uses orders, inventory, email, audit */ return Task.CompletedTask; }
    public Task<byte[]> InvoiceAsync(int id) { /* uses pdf, customers, cache */ return Task.FromResult(Array.Empty<byte>()); }
}

Findings by severity

# Severity Finding Fix
1 Stall / outage new HttpClient() per call: socket exhaustion, no DNS refresh, no resilience Typed client via AddHttpClient<IWarehouseClient, WarehouseClient>() with a resilience handler
2 Wrong data / untestable new TaxCalculator(): tax rules hidden, can't be faked or configured Inject ITaxCalculator
3 Partial failure Email, SMS, PDF and audit inline after the save: an SMS outage fails the request although the order exists Publish OrderPlaced; handle side effects asynchronously (outbox)
4 Diagnostics No CancellationToken; audit as a free-text string Pass ct; structured audit events
5 Design 12 dependencies, three use cases in one class One handler per use case; facade for notifications

The rewrite

See the code example: PlaceOrderHandler takes four dependencies, OrderPlacedNotifications handles the side effects, and WarehouseClient is a typed HttpClient.

How I'd close the review

  • Blocking: finding 1 (production risk) and finding 2 (correctness and tests).
  • Strongly suggested, can be a follow-up PR: split into handlers and move side effects to events.
  • Guard rails: enable CA2000 and the HttpClient analyser rules; add a team guideline that more than ~5 constructor parameters needs a design comment; consider an architecture test (NetArchTest) that flags classes over a threshold.

Production example

In a service like this, a warehouse API slowdown plus new HttpClient() per request pushed the instance to thousands of sockets in TIME_WAIT and caused SocketException errors at about 400 orders per minute. Moving to a typed client fixed the outage; splitting the class later cut the average test setup from around 40 lines to under 10.

🔍 What the interviewer is checking

Checks the candidate ranks review findings by impact and treats constructor over-injection as a design signal with concrete refactoring moves.

Green flags

  • Flags new HttpClient() as the top risk and explains socket exhaustion and DNS
  • Identifies hidden dependencies from new
  • Splits by use case and moves side effects to events
  • Separates blocking findings from follow-up refactoring

Red flags

  • Suggests property injection or a parameter object to shorten the constructor
  • Misses the HttpClient issue
  • Proposes a big-bang rewrite

📚 Learn in depth

1. Why over-injection is a design signal

A constructor lists everything the class touches. Twelve parameters usually means several reasons to change (SRP). Count which methods use which dependency:

              orders customers products email sms pdf discounts audit cache inventory
PlaceAsync      x                  x      x     x   x     x        x            x
CancelAsync     x                         x                        x            x
InvoiceAsync           x                            x                     x

Clusters in that matrix are the classes waiting to be extracted.

2. Refactoring moves

  1. Split by use case: one handler per command (PlaceOrderHandler, CancelOrderHandler, GetInvoiceHandler). Each takes only what it uses.
  2. Domain events for side effects: the handler saves the order and raises OrderPlaced; separate handlers send email, SMS, PDF and audit. With an outbox, the event is stored in the same transaction and processed reliably.
  3. Facade services: when several dependencies always travel together and form one concept (ICustomerNotifier over email + SMS + push), wrap them.
  4. Aggregate services that are just bags (IOrderServiceDependencies) are not a fix; they hide the same coupling.

3. Why new HttpClient() hurts

new HttpClient() → new SocketsHttpHandler → new TCP connections
Dispose()        → socket enters TIME_WAIT (~2-4 min on Windows, ~60 s on Linux by default)
high request rate → ephemeral ports run out → SocketException

IHttpClientFactory pools handlers (default 2-minute handler lifetime), so connections are reused and DNS changes are eventually picked up. A typed client gives a clear dependency and a place for resilience configuration.

4. Hidden new for logic classes

new TaxCalculator() couples OrderService to one implementation and its constructor. It's fine to new value objects and DTOs; it isn't fine for anything with rules that vary, I/O, configuration or time.

Try it yourself

  1. Build a dependency-usage matrix for the largest class in your codebase and identify clusters.
  2. Load test an endpoint that uses new HttpClient() per request and watch TIME_WAIT sockets with netstat or ss -s; then switch to a typed client.
  3. Extract one handler and compare its test setup with the original's.
  4. Add a NetArchTest rule that fails when a class has more than six constructor parameters, and see what it flags.

💻 Code

The refactor: a focused handler, a typed client and an event handler for side effects.

namespace Orders;

// Program.cs registrations
// builder.Services.AddHttpClient<IWarehouseClient, WarehouseClient>(c =>
//         c.BaseAddress = new Uri("https://warehouse.example/"))
//     .AddStandardResilienceHandler();                  // Microsoft.Extensions.Http.Resilience
// builder.Services.AddScoped<ITaxCalculator, GstTaxCalculator>();
// builder.Services.AddScoped<PlaceOrderHandler>();
// builder.Services.AddScoped<IEventHandler<OrderPlaced>, OrderPlacedNotifications>();

public sealed record PlaceOrderCommand(string Email, string Phone, IReadOnlyList<OrderLine> Lines);
public sealed record OrderLine(int ProductId, int Quantity, decimal UnitPrice);
public sealed record OrderPlaced(int OrderId, string Email, string Phone);

// Four dependencies, one reason to change.
public sealed class PlaceOrderHandler(
    IOrderRepository orders, ITaxCalculator tax, IWarehouseClient warehouse, IEventPublisher events)
{
    public async Task<int> HandleAsync(PlaceOrderCommand command, CancellationToken ct)
    {
        var total = tax.Apply(command.Lines.Sum(l => l.UnitPrice * l.Quantity));
        await warehouse.ReserveAsync(command.Lines, ct);
        var id = await orders.AddAsync(command, total, ct);
        await events.PublishAsync(new OrderPlaced(id, command.Email, command.Phone), ct); // via outbox
        return id;
    }
}

// Side effects live in their own handler; a failing SMS no longer fails the order.
public sealed class OrderPlacedNotifications(ICustomerNotifier notifier, IPdfRenderer pdf) : IEventHandler<OrderPlaced>
{
    public async Task HandleAsync(OrderPlaced e, CancellationToken ct)
    {
        await pdf.RenderInvoiceAsync(e.OrderId, ct);
        await notifier.OrderPlacedAsync(e.Email, e.Phone, e.OrderId, ct);
    }
}

// Typed client: pooled handlers, DNS refresh, resilience in one place.
public sealed class WarehouseClient(HttpClient http) : IWarehouseClient
{
    public async Task ReserveAsync(IReadOnlyList<OrderLine> lines, CancellationToken ct) =>
        (await http.PostAsJsonAsync("api/reserve", lines, ct)).EnsureSuccessStatusCode();
}

public interface IWarehouseClient { Task ReserveAsync(IReadOnlyList<OrderLine> lines, CancellationToken ct); }
public interface ITaxCalculator { decimal Apply(decimal subtotal); }
public interface IOrderRepository { Task<int> AddAsync(PlaceOrderCommand c, decimal total, CancellationToken ct); }
public interface IEventPublisher { Task PublishAsync<T>(T e, CancellationToken ct); }
public interface IEventHandler<in T> { Task HandleAsync(T e, CancellationToken ct); }
public interface ICustomerNotifier { Task OrderPlacedAsync(string email, string phone, int orderId, CancellationToken ct); }
public interface IPdfRenderer { Task RenderInvoiceAsync(int orderId, CancellationToken ct); }

⚠ Common mistakes

  • Mistake: Treating the 12 parameters as the problem and the new HttpClient() as a detail. Why it is wrong: the HttpClient can take production down (socket exhaustion, a new TCP and TLS handshake per call adding tens of milliseconds); the parameter count is a maintainability issue. Instead: rank by impact and block on the resource leak first.
  • Mistake: Hiding dependencies behind a parameter object (OrderServiceDependencies). Why it is wrong: the coupling is unchanged and now invisible. Instead: split responsibilities.
  • Mistake: Switching to property injection or IServiceProvider to shorten the constructor. Why it is wrong: dependencies become hidden and failures move to run time. Instead: split the class.
  • Mistake: Replacing new HttpClient() with a static shared instance using default handler settings. Why it is wrong: connections are pooled forever, so the client never sees DNS changes (a problem behind failover or blue-green swaps). Instead: a static or singleton HttpClient is fine and thread-safe if it is built on a SocketsHttpHandler with PooledConnectionLifetime set (for example 2 minutes); otherwise use IHttpClientFactory, which manages handler lifetime for you and adds resilience configuration.
  • Mistake: Creating a facade that just forwards to all twelve services. Why it is wrong: it's a god object one level up. Instead: facades only for cohesive groups.
  • Mistake: Running email, SMS and PDF inline after the database save. Why it is wrong: a notification failure fails a request whose order is already committed, retries create duplicates, and slow providers add their latency to every order. Instead: domain events with an outbox.
  • Mistake: Rewriting everything in one PR. Why it is wrong: risky, hard to review. Instead: block on the bugs, then split handlers incrementally behind the existing API.

🏛 Senior insight: trade-offs

Constructor over-injection is DI doing its job: it makes coupling visible. The senior response is to read the constructor as a map of responsibilities and split along use cases, not to reach for tricks that make the constructor shorter. I also separate what must block the PR (the HttpClient and the hidden calculator) from the design work, which can land incrementally.

Option When it fits Cost When not to
Split into per-use-case handlers Several commands in one service More classes A genuinely single-purpose class that just needs many collaborators (rare)
Domain events + outbox for side effects Notifications, audit, integrations after a commit Eventual consistency, outbox plumbing Side effects that must be in the same transaction
Facade service A cohesive group always used together One more abstraction A bag of unrelated services
Parameter object / property injection Never as a fix for over-injection Hidden coupling Always

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions property injection or long constructors Why: Checks why constructor injection is preferred and the alternatives
    How to answer
    • Constructor injection passes required dependencies to the constructor, so the object is complete and valid the moment it exists and fields can be readonly.
    • Property injection sets dependencies through settable properties after construction; it suits truly optional dependencies but allows half-initialised objects.
    • Method injection passes a dependency only to the method that needs it.

    The built-in container supports constructor injection only, by design: it keeps dependencies explicit and resolution simple. ASP.NET Core adds method-level injection on top: Minimal API handler parameters, [FromServices] on MVC actions, and middleware InvokeAsync parameters. Razor's @inject and Blazor's [Inject] are framework-level property injection.

    The trade-off: constructors make dependencies obvious, but a long constructor is a design smell you can't hide.

  2. When: Candidate mentions splitting the class or composition Why: Checks composition as the basis of the refactor
    How to answer

    Composition means a class has other objects as parts and delegates work to them, instead of inheriting behaviour. A Car has an Engine and Wheels; an OrderProcessor has a validator, a pricer and a notifier. In the strict UML sense, composition also means ownership: the parts are created and destroyed with the whole and are not shared. Benefits: behaviour can be swapped (pass a different IPricingStrategy), combined freely (decorators wrap each other), tested in isolation, and changed without a fragile base class. The cost is a little more wiring, usually handled by constructors or dependency injection.

  3. When: Candidate mentions new HttpClient() or hand-rolled singletons Why: Checks a related review with HttpClient, singletons and factories
    How to answer

    I'd rank the findings by production impact:

    1. Stall or crash. .Result blocks thread-pool threads (starvation). new HttpClient() per call exhausts sockets. A singleton holding a DbContext shares a non-thread-safe context across requests. A plain Dictionary written concurrently can corrupt itself and spin at 100% CPU.
    2. Wrong data. Rates are cached forever, and the switch silently falls back to a default provider.
    3. Security and diagnostics. There's a hard-coded API key, no timeout and no logging.
    4. Design. A racy static Instance hides every dependency, and a switch factory edits the class for each new provider.

    In the rewrite the service is registered with DI. It gets a typed HttpClient with a resilience handler, HybridCache with expiry, a provider chosen once at startup from validated options, an audit writer using IDbContextFactory, async all the way with a CancellationToken, and the secret in Key Vault.

🛠 Real-world problems: how you handle them

Socket exhaustion from an over-injected order service
Situation
An e-commerce order API at [company] handled about [400] orders per minute at peak. OrderService had grown to [12] constructor dependencies and created a new HttpClient per order to reserve stock in the warehouse system.
Signals
During a [sale event], Application Insights showed a spike in SocketException 'Only one usage of each socket address' and HttpRequestException errors on the warehouse dependency; order failure rate rose to [n]%. The SMS provider's brief outage at the same time also failed orders that were already saved.
Investigation
Ran `ss -s` / netstat on the instance and saw thousands of sockets in TIME_WAIT. dotnet-counters showed the System.Net.Http connection counters climbing with traffic. Code search found `new HttpClient()` inside PlaceAsync. Correlated the SMS failures with orders present in the database but reported as failed to the customer.
Resolution
Immediate: hotfix replacing new HttpClient() with a typed client registered through AddHttpClient with the standard resilience handler. Real fix over the next [two] sprints: split OrderService into per-use-case handlers, moved email, SMS, PDF and audit into an OrderPlaced event handler fed by an outbox, and injected ITaxCalculator.
Prevention
Enabled analysers for undisposed and per-call HttpClient patterns, added an architecture test flagging classes with more than six constructor parameters, a load test in CI for the order path, and alerts on dependency failure rate and socket errors.

How to tell it (STAR)

**S:** At [company] our order API started failing during a [sale] at around [400] orders a minute. **T:** I was on call and needed to stop the failures, then make sure the design couldn't do it again. **A:** I saw thousands of TIME_WAIT sockets and traced them to a new HttpClient per order inside a 12-dependency OrderService. I hot-fixed it with a typed client and resilience handler, then led a refactor into per-use-case handlers with notifications moved behind an OrderPlaced event and an outbox, so an SMS outage could no longer fail a committed order. **R:** Socket errors went to zero, order failures during the next peak were [under 0.1%], and the biggest handler went from 12 dependencies to 4.

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me