Dependency Injection in C#

             Dependency Injection is a Software Design Pattern for make Loosely coupled code.There are 3 main ways to implement dependency injection.They are


  1. Constructor Injection
  2. Property Injection
  3. Method Injection
1.Constructor Injection
                            It uses only one Parameterized constructor.

(e.g)

1.
using System;

interface ICar
{
void ShowColor();
}

class Maruthi:ICar
{

public void ShowColor()
{
Console.WriteLine("Maruthi Car");
}
}

class ConstructorInjection
{
   private Maruthi _maruthi;
public ConstructorInjection(Maruthi m)
{
_maruthi=m;
}
public void ShowColor()
{
_maruthi.ShowColor();
}
}

public class Program
{
public static void Main()
{
ConstructorInjection cn = new ConstructorInjection(new Maruthi());
cn.ShowColor();
}
}

2.

public class UserLogic
{
    private GoogleOAuthService _authService;
    private IEmailService _emailService;

    public UserLogic(IEmailSevice emailService)
    {
        _authService = new GoogleOAuthService();
        _emailService = emailService;
    }
    ...
}

...
    GoogleEmailService googleEmailService = new GoogleEmailService();
    UserLogic userLogic = new UserLogic(googleEmailService);
...
      

Output

Maruthi Car


2.Property Injection  
                                   
(e.g)
public class UserLogic
{
    private GoogleOAuthService _authService;
    private IEmailService _emailService;

    public IEmailService EmailService
    {
        get
        {
            return _emailService;
        }
        set
        {
            _emailService = value;
        }
    }

    public UserLogic()
    {
        _authService = new GoogleOAuthService();
    }
    ...

}


...
    OutlookEmailService outlookEmailService = new OutlookEmailService();
    UserLogic userLogic = new UserLogic()
        {
            EmailService = outlookEmailService
        };
...
           
3.Method Injection  

(e.g)
public class UserLogic
{
    private GoogleOAuthService _authService;

    public UserLogic()
    {
        _authService = new GoogleOAuthService();
        _emailService = new OutlookEmailService() // or Google;
    }

    public void Register(string emailAddress, string password, IEmailService emailService)
    {
        var authResult = _authService.RegisterUser(emailAddress,password);
        emailService.SendMail(emailAddress, authResult.ConfirmationMessage);
    }
}

...
    OutlookEmailService outlookEmailService = new OutlookEmailService();
    UserLogic userLogic = new UserLogic();
    userLogic.Register(email, password, outlookEmailService);
...


Comments

Popular posts from this blog

Types of Architects

Basic measurements

Search html table contents based on its td using Jquery