الانتقال إلى المحتوى
Software ArchitectureSOLID· 7 دقائق للقراءة

Dependency Inversion Is Not a DI Container (or an Interface per Class)

The principle decides which way dependencies point and who owns the abstraction. A container only wires objects, and an interface copied from a class keeps the detail's shape.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

Marketing wants order confirmations on WhatsApp as well as email. The solution looks like a SOLID textbook: every class has an 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

The belief: applying the Dependency Inversion Principle means putting an interface in front of every class, registering each pair in a DI container, and receiving everything through constructors.

It's an understandable belief. ASP.NET Core ships with a container, and most tutorials pair 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."

The half-truth: inversion does need an abstraction, and injection is a common way to deliver the implementation. But the container is plumbing, and counting interfaces tells you nothing about which way the dependencies point.

What actually happens

The principle is about direction and ownership

Robert C. Martin's 1996 paper states in two parts: high-level modules should not depend on low-level modules, and both should depend on abstractions; abstractions should not depend on details, and details should depend on abstractions. His first example is a 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!"

Microsoft's guide puts the result in .NET terms: class A calls B at run time, while B depends "on an interface controlled by A at compile time". The interface belongs to the caller. Clean Architecture builds its whole layout on this idea; here we stay at the level of a single dependency.

The policy shapes the abstraction

So what should the abstraction look like? Martin describes high-level policy as "the truths that do not vary when the details are changed." In his button-and-lamp example, the abstraction isn't an 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.

Brett Schuchert, writing on Martin Fowler's site, shows the opposite case: injecting a JDBC connection into a Monopoly game is dependency injection, but at a level far below the game's domain. A board repository is the abstraction that fits.

Header interfaces copy the detail

Fowler names the two kinds of interface. A "is defined by looking at a specific interaction between suppliers and consumers." A mirrors one class, and, as he puts it, "With a header interface all you have to do is duplicate the public methods, no thought needed." 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

Schuchert sums up the three terms in one line: "DI is about wiring, IoC is about direction, and DIP is about shape." Martin made the same point in 2010: "Dependency Injection is just a special case of Dependency Inversion," and it "doesn't require a framework; it just requires that you invert your dependencies and then construct and pass your arguments to deeper layers." His own preference, stated as such: "Most of the time the best kind of Dependency Injection to use, is the manual kind." A container saves you the new calls in the . It can't decide what your interfaces should say.

The fix: let the policy own a narrow interface

C#
// 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);    }}

The ordering code now says what it needs in its own words, and 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.

MythReality
DIP means using a DI containerMartin's 1996 examples pass Reader and Writer as plain parameters; a container is one way to do the wiring
Every class needs an interfaceFowler: use interfaces where you really need substitutability, shaped by the consumer
Extracting an interface inverts the dependencyA header interface keeps the detail's shape; the caller has to own the abstraction
DI and DIP are the same thingSchuchert: DI is about wiring, IoC about direction, DIP about shape
Anything injected through a constructor is invertedInjecting a database connection into game logic is DI with a low-level dependency

How to apply it in your project

  1. Find the header interfacesList 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.
  2. Rewrite boundary interfaces from the caller's sideName 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.
  3. Drop interfaces in front of pure logicCall calculators, policies and mappers directly, and test them directly. Keep an interface only where you need substitutability.
  4. Keep the container at the edgeRegister services in Program.cs, take dependencies through constructors, and keep IServiceProvider out of business code. In unit tests, build the class with new and 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 IServiceProvider or technology words show up in business code, the dependency hasn't been inverted.

📚 المصادر

  1. The Dependency Inversion Principle — Robert C. Martin, The C++ Report (1996)
  2. Dependency Injection Inversion — Robert C. Martin (2010)
  3. DIP in the Wild — Brett L. Schuchert, martinfowler.com (2013)
  4. RoleInterface — Martin Fowler, bliki (2006)
  5. Architectural principles — .NET Architecture Guides, Microsoft Learn

التعليقات (0)