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.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Autofac;
  6. public interface IPayment
  7. {
  8. void Payment();
  9. }
  10. public class CreditCardPaymet : IPayment
  11. {
  12. public void Payment()
  13. {
  14. Console.WriteLine("Redirect to Credit Card Payment");
  15. }
  16. }
  17. public class NetBanking : IPayment
  18. {
  19. public void Payment()
  20. {
  21. Console.WriteLine("Redirect to Net Banking Payment");
  22. }
  23. }
  24. public class DebitCard : IPayment
  25. {
  26. public void Payment()
  27. {
  28. Console.WriteLine("Redirect to Debit Card Payment");
  29. }
  30. }
  31. //Inversion of Control Container
  32. public class GateWay
  33. {
  34. public IPayment objPayment = null;
  35. //Constructor Injection
  36. public GateWay(IPayment tmpPayment)
  37. {
  38. objPayment = tmpPayment;
  39. }
  40. public void SelectedModeOfPayment()
  41. {
  42. objPayment.Payment();
  43. }
  44. }
  45. namespace Client
  46. {
  47. class Program
  48. {
  49. static void Main(string[] args)
  50. {
  51. Console.WriteLine("Execution from conventional IoC");
  52. CreditCardPaymet objPayment = new CreditCardPaymet();
  53. GateWay objGateWay = new GateWay(objPayment);
  54. objGateWay.SelectedModeOfPayment();
  55. //Calling Autofac
  56. CallAutoFac();
  57. }
  58. static void CallAutoFac()
  59. {
  60. Console.WriteLine("Execution from Autofac");
  61. var builder = new ContainerBuilder();
  62. builder.RegisterType<NetBanking>().As<IPayment>();
  63. var container = builder.Build();
  64. container.Resolve<IPayment>().Payment();
  65. Console.ReadLine();
  66. }
  67. }
  68. }

Output:

Class Diagram: