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

الـ Dependency Inversion مش DI container ومش interface لكل class

المبدأ بيحدد الـ dependencies بتشاور على فين، ومين اللي يملك الـ abstraction. أما الـ container فبيوصّل الـ objects ببعض وبس، والـ interface المنسوخة من class بتفضل بشكل الـ detail.

ReadIn

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

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

الـ marketing عايز تأكيد الـ orders يتبعت على WhatsApp جنب الإيميل. والـ solution شكله طالع من كتاب SOLID: كل class ليها توأم بيبدأ بـ I، والـ Program.cs بيسجّل عشرات الأزواج بـ AddScoped. ومع ذلك التغيير بيلمس OrderService و RefundService و ShippingService، لأن كل واحدة فيهم بتبني HTML وبتبعت SMTP settings لـ IEmailSender.SendAsync، ودي interface اتعملها extract من SmtpEmailSender. فيه interface لكل حاجة، والـ business code لسه معتمد على الإيميل.

الفكرة الغلط الشائعة

الفكرة بتقول إن تطبيق الـ Dependency Inversion Principle معناه إنك تحط interface قدام كل class، وتسجّل كل زوج في DI container، وتستلم كل حاجة من الـ constructors.

والفكرة مفهومة. الـ ASP.NET Core جاي ومعاه container، ومعظم الـ tutorials بتحط IFoo جنب Foo في AddScoped<IFoo, Foo>(). والفكرتين مرتبطين فعلًا: الـ architecture guide بتاع Microsoft بيقول "The practice of dependency injection is made possible by following the dependency inversion principle."

النص الصح في الكلام: الـ inversion محتاجة abstraction فعلًا، والـ injection طريقة منتشرة توصّل بيها الـ implementation. بس الـ container سباكة، وعدد الـ interfaces مش بيقول حاجة عن اتجاه الـ dependencies.

اللي بيحصل فعلًا

المبدأ عن الاتجاه والملكية

الـ paper بتاع Robert C. Martin سنة 1996 بيعرّف الـ في جزئين: الـ modules الـ high-level ماتعتمدش على الـ low-level، والاتنين يعتمدوا على abstractions؛ والـ abstractions ماتعتمدش على الـ details، والـ details هي اللي تعتمد عليها. وأول مثال عنده routine اسمها Copy بتقرا من الكيبورد وتكتب على الطابعة، وبعد الـ inversion بتاخد Reader و Writer abstract كـ parameters عادية. مفيش container خالص، ده حتى بيعتبر getchar و putchar بتوع stdio.h في C نفس الحركة: النسخة دي "still uses dependency inversion!"

والـ guide بتاع Microsoft بيقول النتيجة بلغة .NET: الـ class A بتنادي B وقت التشغيل، و B بتعتمد "on an interface controlled by A at compile time". يعني الـ interface ملك الـ caller. والـ Clean Architecture بتبني الـ layout بتاعها كله على الفكرة دي، بس احنا هنا على مستوى dependency واحدة.

الـ policy هي اللي بتحدد شكل الـ abstraction

طب الـ abstraction المفروض يبقى شكلها إيه؟ Martin بيوصف الـ high-level policy إنها "the truths that do not vary when the details are changed." وفي مثال الزرار واللمبة، الـ abstraction مش ILamp. هي ButtonClient فيها TurnOn و TurnOff، لأن الـ policy هي "to detect an on/off gesture from a user and relay that gesture to a target object." اللمبة هي اللي بتعمل implement للـ interface بتاعة الزرار، مش العكس.

و Brett Schuchert، في مقال على موقع Martin Fowler، بيوري الحالة العكسية: لو عملت inject لـ JDBC connection في لعبة Monopoly يبقى ده dependency injection، بس على مستوى أوطى بكتير من الـ domain بتاع اللعبة. والـ abstraction المناسبة هنا board repository.

الـ header interfaces بتنسخ الـ detail

Fowler بيسمّي نوعين من الـ interfaces. الـ "is defined by looking at a specific interaction between suppliers and consumers." أما الـ فبتقلّد class واحدة، وزي ما هو بيقول: "With a header interface all you have to do is duplicate the public methods, no thought needed." والـ IEmailSender من النوع التاني: الـ methods بتاعتها لسه بتتكلم SMTP، فكود الـ orders لسه معتمد على شكل الـ detail، بس دلوقتي قدامه I. ونصيحته: "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."

الـ container مجرد توصيل

Schuchert بيلخّص التلات مصطلحات في سطر: "DI is about wiring, IoC is about direction, and DIP is about shape." و Martin قال نفس الكلام سنة 2010: "Dependency Injection is just a special case of Dependency Inversion," وإنها مش محتاجة framework، كل اللي محتاجاه إنك تعكس الـ dependencies وتبني الـ arguments وتبعتها للطبقات اللي جوه. وده رأيه الشخصي وبيقوله صريح: "Most of the time the best kind of Dependency Injection to use, is the manual kind." الـ container بيوفّر عليك الـ new في الـ ، بس مايقدرش يقرر الـ interfaces بتاعتك تقول إيه.

الحل: خلّي الـ policy تملك 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);    }}

كود الـ orders دلوقتي بيقول هو محتاج إيه بكلامه هو، والـ IOrderNotifications قاعدة جنب PlaceOrder مش جنب SMTP. والـ WhatsApp، أو composite بيبعت على الاتنين، هو adapter زيادة بيتسجّل في Program.cs، والـ PlaceOrder مش بيتغيّر. والـ Pricing خسرت الـ interface بتاعتها: دي policy صافية ليها implementation واحدة، فالـ tests بتناديها على طول. يعني interfaces أقل و inversion أكتر.

الفكرة الغلطالحقيقة
الـ DIP معناه إنك تستخدم DI containerأمثلة Martin سنة 1996 بتبعت Reader و Writer كـ parameters عادية، والـ container طريقة من طرق التوصيل
كل class محتاجة interfaceFowler: استخدم interfaces لما تحتاج تبدّل فعلًا، ويبقى شكلها على قد الـ consumer
إنك تعمل extract لـ interface بيعكس الـ dependencyالـ header interface بتفضل بشكل الـ detail، ولازم الـ caller هو اللي يملك الـ abstraction
الـ DI والـ DIP حاجة واحدةSchuchert: الـ DI عن التوصيل، والـ IoC عن الاتجاه، والـ DIP عن الشكل
أي حاجة جاية من الـ constructor تبقى معكوسةلو عملت inject لـ database connection في logic بتاع لعبة يبقى DI بس بـ dependency من مستوى واطي

تطبقها إزاي في مشروعك

  1. دوّر على الـ header interfacesاعمل لستة بالـ interfaces اللي ليها implementation واحدة والـ methods بتاعتها نسخة منها. واسأل: هي بتحمي detail حقيقي زي I/O أو vendor، ولا class وخلاص؟
  2. اكتب interfaces الحدود من ناحية الـ callerسمّي الـ interface باللي الـ business code محتاجه، واستخدم types من الـ domain في الـ signatures، وانقلها جنب الكود اللي بيناديها. والـ class القديمة تبقى adapter بيعملها implement.
  3. شيل الـ interfaces اللي قدام الـ logic الصافينادي الـ calculators والـ policies والـ mappers على طول، واعملهم test على طول. وسيب interface بس في المكان اللي محتاج فيه تبدّل.
  4. خلّي الـ container على الأطرافسجّل الـ services في Program.cs، وخد الـ dependencies من الـ constructors، وابعد IServiceProvider عن الـ business code. وفي الـ unit tests، اعمل الـ class بـ new ومعاها fake صغير مكتوب بإيدك.

الخلاصة

  • الـ dependency inversion عن الاتجاه والملكية: الـ policy بتعتمد على abstraction هي اللي تملكها، والـ details هي اللي بتعملها implement.
  • الـ DI container مجرد توصيل، وأمثلة Martin نفسه بتبعت الـ abstractions كـ parameters عادية.
  • الـ interface المنسوخة من class بتفضل بشكل الـ detail، فصمّمها على قد اللي الـ caller محتاجه.
  • ضيف interfaces في المكان اللي الـ policy بتقابل فيه detail أو محتاجة تبدّل، مش قدام كل class.
  • لو IServiceProvider أو كلام عن التكنولوجيا ظهر في الـ business code، يبقى الـ dependency لسه ماتعكستش.

📚 المصادر

  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)