Now a days I am experimenting with various IoC containers and trying to implement POC and sharing with the community. This article assumes a basic understanding of de-coupled architecture and the concept of Inversion of Control. In our previous article we talked about Unity and Ninject, you can read them here.
We know that IoC stands for Inversion of Control and it's a way to implement more independent components and to make the work easy, there are many IoC containers in the market, Autofac is one of them. In this article we will try to implement a simple example of dependency injection using Autofac. First of all create one Console application to implement the sample example and provide a reference of Autofac from the NuGet Package Manager. Here is the package.
Once you provide a reference, you will find the following reference in the references section of the application.
We are now ready to implement the IoC container using autofac. Have a look at the following example. At first we have implemented two interfaces and it's corresponding concrete class.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Autofac;
-
- public interface IMobileServive
- {
- void Execute();
- }
- public class SMSService : IMobileServive
- {
- public void Execute()
- {
- Console.WriteLine("SMS service executing.");
- }
- }
-
- public interface IMailService
- {
- void Execute();
- }
-
- public class EmailService : IMailService
- {
- public void Execute()
- {
- Console.WriteLine("Email service Executing.");
- }
- }
-
- public class NotificationSender
- {
- public IMobileServive ObjMobileSerivce = null;
- public IMailService ObjMailService = null;
-
-
- public NotificationSender(IMobileServive tmpService)
- {
- ObjMobileSerivce = tmpService;
- }
-
- public IMailService SetMailService
- {
- set { ObjMailService = value; }
- }
- public void SendNotification()
- {
- ObjMobileSerivce.Execute();
- ObjMailService.Execute();
- }
- }
-
- namespace Client
- {
- class Program
- {
- static void Main(string[] args)
- {
- var builder = new ContainerBuilder();
- builder.RegisterType<SMSService>().As<IMobileServive>();
- builder.RegisterType<EmailService>().As<IMailService>();
- var container = builder.Build();
-
- container.Resolve<IMobileServive>().Execute();
- container.Resolve<IMailService>().Execute();
- Console.ReadLine();
- }
- }
- }
We have then implemented a NotificationSender class that is dependent on both MobileService and MailService.
We have injected a dependency of both classes through constructor and property. Have a look at the Main() function where we have created a repository of all dependency types and building the repository. Once we run the application we will see the following result.
ConclusionThere are many IoC containers available in the market and Autofac is one of them. All the containers have some pros and cons and none of them are perfect, so the choice is yours.