I‘ll discuss about dependency injection pattern and its implementation using Microsoft Unity Application Block. First we start with what is Dependency Injection.
What is Dependency Injection?
DI is also known as Inversion of Control (IOC). It is a design pattern that remove tight coupling between dependent components. It facilitates the design and implementation of loosely coupled, reusable, and testable objects in your software designs by removing dependencies that often inhibit reuse. Instead of compile time dependencies it offers runtime loading and initialization of components, which makes solutions load on demand.
There are following advantages and disadvantages of Dependency Injection
Primary advantages:
- Loose coupling
- Centralized configuration
- Easily testable
Disadvantages:
- Debugging components while development because finding concrete objects may be tedious task.It make code harder to understand and more difficult to modify.
- Wiring instances together can become a nightmare if there are too many instances and many dependencies that need to be addressed.
Different types of Dependency Injection
- Constructor Injection
- Setter Injection
- Interface-based injection
Constructor Injection
In this injection type, dependencies can be injected through parameters in constructor of class. It is widely used in Unit Testing with Mocking objects.
Here is example (Please note: this example is not real solution of credit card validation, it is just for example purpose).
public class CreditCardValidator
{
private ICreditCard _card;
public CreditCardValidator(ICreditCard card)
{
_card = card;
}
public bool Validate()
{
return _card.Validate();
}
}
In below code I am injecting instance of VisaCard and MasterCard classes from outside to validate card no.
public interface ICreditCard
{
string CardNo { set; }
bool Validate();
}
public class MasterCard : ICreditCard
{
private string _cardno;
public bool Validate()
{
return true;
}
public string CardNo
{
set { _cardno = value; }
}
}
public class VISA : ICreditCard
{
private string _cardno;
public bool Validate()
{
return true;
}
public string CardNo
{
set { _cardno = value; }
}
}
static void Main(string[] args)
{
ICreditCard visaCard = new VISA();
visaCard.CardNo = "123123123";
ICreditCard mastercard = new MasterCard();
visaCard.CardNo = "456456456";
Console.WriteLine("Validate Card");
CreditCardValidator validator = new CreditCardValidator(visaCard);
Read more: Beyond Relational