Tuesday, July 8, 2014

Inversion of control and Dependency injection – Design Pattern

I am going to show you a very simple example on IoC (Inversion of Control) and DI (Dependency Injection). I will show you problem, solution based on design pattern and implementation based on design pattern.

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

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...