
الـ Dependency Inversion مش DI container ومش interface لكل class
- كاتب موثّق
محتويات المقال
I، والـ Program.cs بيسجّل عشرات الأزواج بـ AddScoped. ومع ذلك التغيير بيلمس OrderService و RefundService و ShippingService، لأن كل واحدة فيهم بتبني HTML وبتبعت SMTP settings لـ IEmailSender.SendAsync، ودي interface اتعملها extract من SmtpEmailSender. فيه interface لكل حاجة، والـ business code لسه معتمد على الإيميل.
الفكرة الغلط الشائعة
IFoo جنب Foo في AddScoped<IFoo, Foo>(). والفكرتين مرتبطين فعلًا: الـ architecture guide بتاع Microsoft بيقول "The practice of dependency injection is made possible by following the dependency inversion principle."
اللي بيحصل فعلًا
المبدأ عن الاتجاه والملكية
Copy بتقرا من الكيبورد وتكتب على الطابعة، وبعد الـ inversion بتاخد Reader و Writer abstract كـ parameters عادية. مفيش container خالص، ده حتى بيعتبر getchar و putchar بتوع stdio.h في C نفس الحركة: النسخة دي "still uses dependency inversion!"
الـ policy هي اللي بتحدد شكل الـ 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 بتاعة الزرار، مش العكس.
الـ header interfaces بتنسخ الـ detail
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 مجرد توصيل
new في الـ ، بس مايقدرش يقرر الـ interfaces بتاعتك تقول إيه.
الحل: خلّي الـ policy تملك 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 قاعدة جنب PlaceOrder مش جنب SMTP. والـ WhatsApp، أو composite بيبعت على الاتنين، هو adapter زيادة بيتسجّل في Program.cs، والـ PlaceOrder مش بيتغيّر. والـ Pricing خسرت الـ interface بتاعتها: دي policy صافية ليها implementation واحدة، فالـ tests بتناديها على طول. يعني interfaces أقل و inversion أكتر.
Reader و Writer كـ parameters عادية، والـ container طريقة من طرق التوصيل | |
تطبقها إزاي في مشروعك
دوّر على الـ header interfaces اعمل لستة بالـ interfaces اللي ليها implementation واحدة والـ methods بتاعتها نسخة منها. واسأل: هي بتحمي detail حقيقي زي I/O أو vendor، ولا class وخلاص؟ اكتب interfaces الحدود من ناحية الـ caller سمّي الـ interface باللي الـ business code محتاجه، واستخدم types من الـ domain في الـ signatures، وانقلها جنب الكود اللي بيناديها. والـ class القديمة تبقى adapter بيعملها implement. شيل الـ interfaces اللي قدام الـ logic الصافي نادي الـ calculators والـ policies والـ mappers على طول، واعملهم test على طول. وسيب interface بس في المكان اللي محتاج فيه تبدّل. خلّي الـ 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 لسه ماتعكستش.
📚 المصادر
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)