Sunday, 6 March 2016

Dependency Injection in C# with Example




Dependency Injection (DI) is a design pattern that take away from the responsibility by creating a dependency class to create  loosely coupled system.Most people not clear idea about what is dependency injection (DI) and when it want to use in the code.

In this article i'm taring to describe what is dependency Injection(DI) and how we use to get loosely coupled system using simple example.Imagine you have face situation like follow


you have class Employee and it has Logger for print message.and also you have to add another Logger method for different customer,normally we can implement that as follow.

public class Employee
{
    private LoggerOne LoggerOne;
    private LoggerTwo LoggerTwo;

}

public class LoggerOne
{
    public void WriteToLog(string text)
    {
        Console.WriteLine(text);
    }
}

public class LoggerTwo
{
    public void WriteToLog(string text)
    {
        Console.WriteLine("***********\n {0}\n***********",text);
    }
}

 but in this implementation Employee class tightly coupled with  LoggerOne and LoggerTwo.So this system hard to modify and reuse.

So prevent that issue we can use dependency Injection to solve this and get loosely coupled system.

  
We can use interface ILogger class for the Logger to inject the dependency to Employee class as follow

public class Employee
{
    private ReadOnly ILogger _logger;
    public Employee(ILogger Logger){
 
       _logger=Logger;
       _logger.WriteToLog("Test Logger");
    }

}

public interface ILogger
{
    void WriteToLog(string text);
}

public class LoggerOne : ILogger
{
    public void WriteToLog(string text)
    {
        Console.WriteLine(text);
    }
}

public class LoggerTwo : ILogger
{
    public void WriteToLog(string text)
    {
        Console.WriteLine("***********\n {0}\n***********", text);
    }
}
Now let's instantiate an Employee with two different loggers:

 Employee employee1 = new Employee(new LoggerOne());
 Employee employee2 = new Employee(new LoggerTwo());

 And the output:

 Test Logger

*******************
Test Logger
******************

Share:

Friday, 28 August 2015

SOLID Principal in C#


Solid principal is contains five basic principal  of OOP  and design to create good software architecture.By using these basic principal we can design, create a system that can easily maintain and extensible over time.It is part of an overall strategy of agile and adaptive programming.

SOLID is an acronym where
  • S: Single Responsibility Principle (SRP)
  • O: Open closed Principle (OSP)
  • L: Liskov substitution Principle (LSP)
  • I: Interface Segregation Principle (ISP)
  • D: Dependency Inversion Principle (DIP)





Share: