This document discusses dependency injection and how it can be implemented using Ninject as a dependency injection container. Dependency injection allows removing hard-coded dependencies and making it possible to change dependencies at runtime or compile-time. It describes how a booking class can be decoupled from its dependencies like email and SMS notification classes by injecting them through the constructor instead of creating them internally. Ninject is then introduced as a dependency injection container that can further remove the need to manually inject dependencies and make the code less tightly coupled.
2. What is Dependency Injection?
▪ Dependency Injection is a software design pattern that
allows the removal of hard coded dependencies and makes
it possible to change them, whether at run-time or
compile-time.
3. Dependency Injection
▪ One of the requirement was: System should able to book seat. And
after booking confirmation email should go to customer.
▪ To send emails we have created class we have created class Email
Notification with a method SendEmail()
4. Dependency Injection
▪ To send notification; Book() method is calling SendEmail() method of
EmailNotification class.
▪ Here Booking class internally use EmailNotificationclass. Such
classes are said to be tightly coupled
10. Dependency Injection
▪ Classes should always communicateWith each other via Interfaces.
▪ Interface INotification with a method declaration SendMessage()
12. Dependency Injection
▪ Call method of EmailNotification from Booking using reference of
INotification interface.
13. Dependency Injection
▪ Using interfaces we have Decoupled Booking and EmailNotification
classes.
▪ Still there is dependency of EmailNotification in Booking class. As we
are creating object of EmailNotification inside Booking class.
14. Dependency Injection
▪ Can we move this dependency out of Booking class?
▪ Yes, with the help of
Inversion of Control (IoC)
or
Dependency Injection
15. Dependency Injection
▪ Instead of creating object of EmailNotification in Booking class we
will pass it via constructor.
16. Dependency Injection
▪ To create Object of Booking class in HomeController, we need to
Inject object of EmailNotification to constructor of Booking.
17. Dependency Injection
▪ To create Object of Booking class in HomeController, we can also
Inject object ofSMSNotification to constructor of Booking.
19. Dependency Injection
But there are 2 problems…
1. We are manually injecting dependency into Booking class by
providing the implementation for INotification interface.
2. We are creating EmailNotification or SMSNotification in
HomeController; making HomeController tightly coupled with
these classes.
But there problems can be resolved using…
DI Container