Problem: Tight Coupling
Public Class Customer Private objOrder As Order Public Sub New() objOrder = New Order 'Issue: Aware of concrete class' End Sub End Class Public Class Order End Class
Solution: Inversion of Control
Public Class Customer Private objOrder As Order Public Sub New(ByVal objO As Order) 'IoC concept: Passing Object' objOrder = objO 'instead of creating it' End Sub End Class Public Class Order End Class Sub Main() Dim objOrder As New Order Dim objCustomer As New Customer(objOrder) End Sub
Implementation: Dependency Injection
So, basically IoC is a principal and DI is implementation way. You can implement DI in four different way.
1. A constructor injection
2. Parameter injection
3. A setter injection
4. An Interface injection
So following is the example of “Constructor Injection”.
Public Class Customer Private iDOrder As IDairyOrder Public Sub New(ByVal objDOrder As IDairyOrder) 'Passing Interface' iDOrder = objDOrder 'Instead of passing concreate class object' End Sub End Class Public Interface IDairyOrder End Interface Public Class Order1 Implements IDairyOrder End Class Public Class Order2 Implements IDairyOrder End Class Sub Main() Dim iDOrder as IDairyOrder iDOrder = New Order1 Dim objCustomer As New Customer(iDOrder) iDOrder = New Order2 objCustomer = New Customer(iDOrder) End Sub
No comments:
Post a Comment