C#C
C#2y ago
textYash

Purpose of Dependency Injection

In this example what's the benefit of DI here. I can just create instances of EmailService and MessagingService class and call the SendMessage method on them without having to create an extra instance of the NotificationService class.

namespace basic_programs{
    interface IMessagingService {
        string SendMessage(string message);
    }
    class EmailService : IMessagingService {
        public string SendMessage(string message) {
            return $"Email sent: {message}";
        }
    }
    class SMSService : IMessagingService {
        public string SendMessage(string message) {
            return $"SMS sent: {message}";
        }
    }
    class NotificationService(IMessagingService messaging_service)
    {
        private readonly IMessagingService _messagingService = messaging_service;

        public string SendNotification(string message) {
            return _messagingService.SendMessage(message);
        }
    }
    class Lab23 {
        public static void NotificationDemo() {
            NotificationService email_service = new(new EmailService());
            NotificationService sms_service = new(new SMSService());
            System.Console.WriteLine(email_service.SendNotification("Hello"));
            System.Console.WriteLine(sms_service.SendNotification("Hello"));
        }
    }
}


I asked AI then it just mentioned:
  1. some theoretical information about how DI has loose coupling and all but couldn't prove any benefit in the code.
  2. how I can independently test the NotificationService but I can just independently test MessagingService & EmailService.
  3. how adding features to the MessagingService & EmailService can cause problems but couldn't show me how it can cause problems in the code.
Was this page helpful?