
Dependency Inversion Is Not a DI Container (or an Interface per Class)
- كاتب موثّق
محتويات المقال
I-prefixed twin, and Program.cs registers dozens of pairs with AddScoped. Yet the change touches OrderService, RefundService and ShippingService, because each one builds HTML and passes SMTP settings to IEmailSender.SendAsync, an interface extracted from SmtpEmailSender. There's an interface for everything, and the business code still depends on email.
The common misconception
IFoo with Foo in AddScoped<IFoo, Foo>(). The ideas really are related: Microsoft's architecture guide says "The practice of dependency injection is made possible by following the dependency inversion principle."
What actually happens
The principle is about direction and ownership
Copy routine that reads from a keyboard and writes to a printer. Inverted, Copy takes an abstract Reader and Writer as plain parameters. There's no container anywhere, and he even counts C's getchar and putchar from stdio.h as the same move: that version "still uses dependency inversion!"
The policy shapes the abstraction
ILamp. It's a ButtonClient with TurnOn and TurnOff, because the policy is "to detect an on/off gesture from a user and relay that gesture to a target object." The lamp implements the button's interface, not the other way around.
Header interfaces copy the detail
IEmailSender is the second kind: its methods still talk SMTP, so the order code still depends on the detail's shape, now with an I in front. His advice: "you should only use interfaces when you really need substitutability, and if you do need interfaces you should think hard about what the consumer of that interface needs."
The container is only wiring
new calls in the . It can't decide what your interfaces should say.
The fix: let the policy own a narrow interface
// Extracted from SmtpEmailSender, so it speaks SMTPpublic interface IEmailSender{ Task SendAsync(string to, string subject, string html, SmtpSettings smtp);}// One implementation, ever, but it got an interface toopublic interface IPriceCalculator { decimal Total(Order order); }public sealed class OrderService( IEmailSender email, IPriceCalculator prices, SmtpSettings smtp){ public Task PlaceAsync(Order order) { // Business code builds HTML and picks SMTP settings var html = $"<p>Order {order.Id}: {prices.Total(order):C}</p>"; return email.SendAsync( order.CustomerEmail, "Order placed", html, smtp); }}// Owned by the ordering code and named for what it needspublic interface IOrderNotifications{ Task OrderPlacedAsync(Order order, decimal total, CancellationToken ct);}public static class Pricing // pure policy: no interface needed{ public static decimal Total(Order o) => o.Lines.Sum(l => l.Price * l.Qty);}public sealed class PlaceOrder(IOrderNotifications notifications){ public Task RunAsync(Order order, CancellationToken ct) => notifications.OrderPlacedAsync(order, Pricing.Total(order), ct);}// The detail adapts itself to the policy's interfacepublic sealed class EmailOrderNotifications(SmtpSender smtp) : IOrderNotifications{ public Task OrderPlacedAsync(Order o, decimal total, CancellationToken ct) => smtp.SendAsync(o.CustomerEmail, "Order placed", $"{total:C}", ct);}IOrderNotifications lives next to PlaceOrder, not next to SMTP. WhatsApp, or a composite that sends both, is one more adapter registered in Program.cs, and PlaceOrder doesn't change. Pricing lost its interface: it's pure policy with one implementation, so tests call it directly. Fewer interfaces, more inversion.
Reader and Writer as plain parameters; a container is one way to do the wiring | |
How to apply it in your project
Find the header interfaces List interfaces with exactly one implementation whose methods mirror that class. For each, ask whether it guards a real detail, such as I/O or a vendor, or just a class. Rewrite boundary interfaces from the caller's side Name the interface for what the business code needs, use domain types in its signatures, and move it next to the code that calls it. The old class becomes an adapter that implements it. Drop interfaces in front of pure logic Call calculators, policies and mappers directly, and test them directly. Keep an interface only where you need substitutability. Keep the container at the edge Register services in Program.cs, take dependencies through constructors, and keepIServiceProviderout of business code. In unit tests, build the class withnewand a small hand-written fake.
Key takeaways
Dependency inversion is about direction and ownership: policy depends on an abstraction it owns, and details implement it. A DI container is wiring; Martin's own examples pass abstractions as plain parameters. An interface copied from a class keeps the detail's shape; design it around what the caller needs. Add interfaces where policy meets a detail or needs substitutability, not in front of every class. If IServiceProvideror technology words show up in business code, the dependency hasn't been inverted.
📚 المصادر
The Dependency Inversion Principle — Robert C. Martin, The C++ Report (1996) Dependency Injection Inversion — Robert C. Martin (2010) DIP in the Wild — Brett L. Schuchert, martinfowler.com (2013) RoleInterface — Martin Fowler, bliki (2006) Architectural principles — .NET Architecture Guides, Microsoft Learn
التعليقات (0)