Basics of Autofac: How to implement it in .NET?

10 May 2021 at 10:00 by ParTech Media - Post a comment

If you have used dependency injection in the past, you must know why it is pretty useful. Dependency injection provides loose coupling and aids in maintaining and testing an application.

Dependency injection and IoC concepts form the core of most object-oriented applications.

IoC is a generic term that implies the flow of control as: Instead of calling the methods in a framework, the framework calls the implementations provided by the application.

Dependency injection offers developers immense control over their applications, bestowing them with some of the best features such as configurations along with the independence of classes. This dependency injection is provided by a DI container in .NET. It comes prebuilt and requires no additional installation.

But a third-party DI container can offer more than this. This is the prime reason why developers are adopting a third-party DI container over prebuilt ones for large-scale applications. AutoFac is a powerful third-party DI container used widely among .NET developers. Let us dive deeper into what is Autofac and why it is useful.

Table of contents

  • Some background
  • What is Autofac?
  • Benefits of Autofac over built-in DI container
  • Practical implementation of Autofac
  • Conclusion

Background

Dependency injection is a form of IoC(Inversion of control) in which implementations are passed through constructors or setters on which the application clings on to function correctly.

In other words, it is a programming technique that allows classes to stay independent of their dependencies. This gives developers a good amount of control over multiple classes. This dependency injection is provided by a prebuilt DI container or a third-party DI container. But when it comes to developing enterprise-scale applications, developers always seek the aid of third-party DI containers such as AutoFac.

What is AutoFac?

AutoFac is an Inversion of Control container that resolves dependencies of an application. This means that it also is a dependency injection framework.

If you are not familiar with this idea in the object-oriented world, it is a way of injecting dependencies that are relied upon by other classes usually in a constructor. Autofac has the reputation of being the most widely used framework in the .NET community. It is one of the most downloaded packages among developers. AutoFac provides better integration for the ASP.NET MVC framework and is developed using Google code.

AutoFac manages the dependencies of classes so that the application may be easy to change when it is scaled up in size and complexity. Let us peek into why the built-in DI container is being replaced by AutoFac.

Benefits of AutoFac over built-in DI container

  1. The .NET DI container does not help in verifying the configuration, leaving it very difficult to spot problems that arise from common misconfigurations. In large-scale applications, it is hard to spot misconfigurations yourself.
  2. The .NET DI container offers only one constructor injection.
  3. Using AutoFac, access to new features such as property injection is made possible that the built-in IoC container lacks.
  4. The inbuilt container is very light and is the default container for basic applications. Users can easily switch to third-party IoC containers such as AutoFac or structuremap.
  5. AutoFac supports a wide variety of application designs with minimum additional infrastructure and integration code, with a lower learning curve.
  6. Implementing a third-party IoC container like AutoFac can result in reusable code, more readable code, and easily testable code, centralizing the logic for dependency management.
  7. Autofac covers all the features offered by IoC containers, and also other subtle features that help with the application configuration, managing the life cycles of components, and managing multiple dependencies under your watch.

Practical implementation of AutoFac

As we have constantly highlighted in this blog, to unlock the full benefits of dependency injection it is always better to use a third-party DI container rather than having an inbuilt DI container. From managing runtime dependencies to being open source, Autofac is an indispensable resource for developers working in .NET.

Let us now perform a simple dependency injection using AutoFac.

Step 1

Open Visual Studio and create a new project. Choose the console app(.NET Core) from the list of runtime environments specified. The console application is for creating a command-line interface that can run on .NET Core. You also have the liberty to choose a web application based on which your project will be built.

Step 2

The next step is to configure your project. Specify the name of your project and the location where you want your project to be hosted. Proceed to CREATE.

Step 3

The Visual Studio now automatically creates the default Hello world program, a console application.

Before we begin our task, it is necessary to add the third-party DI container extension. Go to the solution explorer tab on the right corner of the project. Right-click on dependencies and choose the manage NuGet packages. Now install the AutoFac package by searching through the search packages bar.

Step 4

Now that AutoFac is installed, let us implement dependency injection using AutoFac. The following is a simple console application involving the implementation of dependency injection using AutoFac.

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("Partech SMS service executing.");

  }

}



public interface IMailService

{

  void Execute();

}



public class EmailService : IMailService

{

  public void Execute()

  {

​    Console.WriteLine("Partech Email service Executing.");

  }

}



public class NotificationSender

{

  public IMobileServive _mobileSerivce = null;

  public IMailService _mailService = null;



  //injection through constructor  

  public NotificationSender(IMobileServive tmpService)

  {

​    _mobileSerivce = tmpService;

  }

  //Injection through property  

  public IMailService SetMailService

  {

​    set { _mailService = value; }

  }

  public void SendNotification()

  {

​    _mobileSerivce.Execute();

​    _mailService.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();

​    }

  }

}

Here we have implemented two interface classes and their corresponding concrete classes.

Then we have implemented a notification sender class that is dependent on both mailService and mobileService. We have injected a dependency of both the classes through a constructor. Have a look at the Main() function to see a repository of dependency types and build the repository.

Here is the output of the code -

Conclusion

To make classes independent of their dependencies, it is wise to use dependency injection. It enables you to replace or change the dependencies without disrupting the class components or the main code. So for small-scale applications, the built-in DI container can be used. But when it comes to large-scale remote applications, Autofac is the go-to choice as it offers a plethora of features that the built-in DI container of .NET lacks.

Latest