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.
The 12-parameter constructor is a symptom: the class has several responsibilities (placing, cancelling, notifying, invoicing, auditing). The new calls are the bugs.
new HttpClient() in a method: socket exhaustion under load and stale DNS. Use IHttpClientFactory or a typed client.new TaxCalculator(): a hidden dependency that can't be faked or configured. Inject it.The trade-off: more, smaller classes, in exchange for code where each class can be understood and tested on its own.
"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 withIHttpClientFactoryor a typed client before anything else. Next isnew 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 anOrderPlacedevent, ideally via an outbox so a failing SMS doesn't roll back an order. If email, SMS and push really belong together, a smallICustomerNotifierfacade is fine.The mistake I see is hiding the smell instead of fixing it: property injection, a
ServiceDependenciesparameter object holding all twelve, or injectingIServiceProvider. All of those keep the coupling and just make it harder to see."
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>()); }
}
| # | 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 |
See the code example: PlaceOrderHandler takes four dependencies, OrderPlacedNotifications handles the side effects, and WarehouseClient is a typed HttpClient.
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.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.
Checks the candidate ranks review findings by impact and treats constructor over-injection as a design signal with concrete refactoring moves.
Green flags
new HttpClient() as the top risk and explains socket exhaustion and DNSnewRed flags
HttpClient issueA 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.
PlaceOrderHandler, CancelOrderHandler, GetInvoiceHandler). Each takes only what it uses.OrderPlaced; separate handlers send email, SMS, PDF and audit. With an outbox, the event is stored in the same transaction and processed reliably.ICustomerNotifier over email + SMS + push), wrap them.IOrderServiceDependencies) are not a fix; they hide the same coupling.new HttpClient() hurtsnew 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.
new for logic classesnew 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.
new HttpClient() per request and watch TIME_WAIT sockets with netstat or ss -s; then switch to a typed client.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); }
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.OrderServiceDependencies). Why it is wrong: the coupling is unchanged and now invisible. Instead: split responsibilities.IServiceProvider to shorten the constructor. Why it is wrong: dependencies become hidden and failures move to run time. Instead: split the class.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.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 |
readonly.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.
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.
I'd rank the findings by production impact:
.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.switch silently falls back to a default provider.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.
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.
Last updated 23 Nov 2026.