Dependency injection is a software design pattern that
implements inversion of control for resolving dependencies.
In terms, we can refer Dependency as an object which can be
served as a Service and Injection is referred as passing of a dependency to a
client object that would use it. Remember that the Service is made part of
client’s state.
Below example demonstrates the purpose of Inversion of
Control (IoC) and Autofac (IoC container).
First of All, what is Autofac?
Autofac is an addictive Inversion of Control container
for .NET 4.5.
If you look at the below code, you can clearly see that GateWay class which
is a conventional IoC container is not called in Autofac whereas Autofac uses ContainerBuilder to
execute Payment method.
For downloading Autofac, use Nuget Package Manager.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Autofac;
-
- public interface IPayment
- {
- void Payment();
- }
-
- public class CreditCardPaymet : IPayment
- {
-
- public void Payment()
- {
- Console.WriteLine("Redirect to Credit Card Payment");
- }
- }
-
- public class NetBanking : IPayment
- {
- public void Payment()
- {
- Console.WriteLine("Redirect to Net Banking Payment");
- }
- }
-
- public class DebitCard : IPayment
- {
- public void Payment()
- {
- Console.WriteLine("Redirect to Debit Card Payment");
- }
- }
-
-
- public class GateWay
- {
- public IPayment objPayment = null;
-
-
- public GateWay(IPayment tmpPayment)
- {
- objPayment = tmpPayment;
- }
-
- public void SelectedModeOfPayment()
- {
- objPayment.Payment();
- }
- }
-
- namespace Client
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Execution from conventional IoC");
- CreditCardPaymet objPayment = new CreditCardPaymet();
- GateWay objGateWay = new GateWay(objPayment);
- objGateWay.SelectedModeOfPayment();
-
- CallAutoFac();
- }
-
- static void CallAutoFac()
- {
- Console.WriteLine("Execution from Autofac");
- var builder = new ContainerBuilder();
- builder.RegisterType<NetBanking>().As<IPayment>();
- var container = builder.Build();
- container.Resolve<IPayment>().Payment();
- Console.ReadLine();
- }
- }
- }
Output:
Class Diagram: