Introduction to Dependency Injection with Autofac

|  Posted: July 19, 2019  |  Categories: Angular General

Before blowing anyone’s mind with the capabilities of Autofac, let’s first get the basics right. Why Autofac? What is Autofac? What do you need to know before you jump into your code and add the Nuget.

The Hollywood principle

The basic idea right before we goto Autofac is that Don’t call us, we’ll call you. In c# Terms Don’t call around for your dependencies, we’ll give them to you whenever we need you.

Let’s get our basics right first before we do anything.

What is dependency Injection

  1. Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic.
  2. Each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies).

There are a lot of ways in which dependency Injection can be done. Here are some of them.

  • Constructor Injection
  • Setter Injection
  • Interface-based injection
  • Service Locator Injection

But in this blog, we will look at the Constructor Injection pattern.

Containers / IOC

We need a container to manage all the objects throughout the lifetime of the request. It manages object creation and it’s life-time, and also injects dependencies to the class. There are a lot of container libraries available. Here’s a list of some of the most popular libraries sorted in no order

  • Castle Windsor
  • StructureMap
  • Spring.NET
  • Autofac
  • Unity
  • Puzzle.Nfactory
  • Ninject
  • S2Container.NET
  • PicoContainer.NET
  • LinFu

In this blog, we are going with Autofac and we will also go through some of the common things that we need. In any application, there is a

  • Object to DB Mapping code
  • Logging code using any Logger
  • Number of Services and Repositories

In our previous blog @Suhas covered on how to simplify the Object->DB mapping code using a library called AutoMapper. Now let’s inject it and have more fun with it 🙂

Remember AutoMapper Profiles from @suhas blog? Yes, we can create any number of profiles. But wait, what if we have 100 profiles on an enterprise application?

var mapperConfiguration = new MapperConfiguration(config =>
        {
            config.AddProfile(new ProfileA());
            config.AddProfile(new ProfileB());
        });

Now a question arises in your mind, O__o what ??? Do I need to register 100 profiles like this?

NOPE, WE ARE NOT DOING IT. SAY NO TO DUPLICATING CODE 🙂

Configuring Autofac

  • Install the Nuget and the easiest way to get started with Autofac is to follow their docs and get it up and running based on your setup.

Here’s where Automapper comes into place, we create an AutomapperModule class which inherits Autofac.Module and give it any class which inherits AutoMapper.Profile

Yah! How simple was that? 16 Lines of code, you now have given AutoMapper whatever it needs for Mapping to be done and also we have told Autofac to resolve Automapper. Now it can be accessed in the constructor of any class. Example below

Resolving a Logger

Every application has some logging to find out what’s going on when the application is being executed. You can have any type of Logger in your application.

In any class/ Controller wherever you need your logger, what people do is either put

Logger = LogProvider.GetCurrentClassLogger(); or
var logger = new Logger();

This is the common way of doing this. But when I searched for the 2nd line I found more than 1000 instances of Logger objects being created in more than 100 classes, controllers, repositories, etc.

Now let’s remove all the duplicated code and revolve Logger only once using Autofac and make it available anywhere.

	builder.RegisterInstance(LogProvider.GetCurrentClassLogger()).As<ILog>();

That’s it. Only one line. Now you can inject logger similar to Mapper.

References

Autofac documentation – https://autofaccn.readthedocs.io

Automapper documentation – https://automapper.org

Conclusion

SAY NO TO CODE DUPLICATION, SAY HELLO TO DEPENDENCY INJECTION 🙂

Similarly, you can resolve any Service/Repository and it can be injected into the constructor of any class. There are a lot of best practices which can be followed. I will try to cover it in the upcoming blogs.

Author: Hariharan subramanian

Junior Software Engineer. CSharp Enthusiast, Azure Functions, passionate about Biking and Travelling.

Get notified about any future events

Interested in learning more about TechMeet360 or knowing about any future events? Sign up below to get notified.

Back to Top