Writing modular and testable code is important. One powerful technique that helps in attaining this goal is dependency injection (DI). Dependency injection allows us to pass dependencies (services or objects) into a class instead of creating them within the class, enabling loose coupling and making our code more maintainable and testable.
In this Answer, we’ll see how to use Autofac in C#, but we need prior knowledge of basic syntax, dependency inject, and interfaces.
Autofac is an open-source dependency injection package for .NET applications. It simplifies managing object creation and helps organize our application’s components.
We can install Autofac using .NET CLI or a package manager like NuGet.
Open the terminal, navigate to the project folder, and execute the command below:
dotnet add package Autofac
Note: We can run the command above in the terminal integrated in the playground below.
The basic configuration of Autofac works on the principle of registration and resolution. It registers all the dependencies in the centralized container and resolves the dependency when some component requires this service:
We need to create a container that registers the services by using the following syntax:
using Autofac;// Container buildervar builder = new ContainerBuilder();
The builder
function is an instance of ContainerBuilder
class from Autofac
namespace to register the services.
After creating builder
we need to register components (services, dependencies, or objects) in the container. This is typically done during the application’s start-up:
// Registering a componentbuilder.RegisterType<MyService>().As<IMyService>();// Build the container after registrationvar container = builder.Build();
The RegisterType<>()
function registers the type MyService
with the container. This means that Autofac is aware of its existence and can provide instances of it when requested.
The As<IMyService>()
function specifies that when someone asks Autofac for an instance of IMyService
, it should provide an instance of MyService
. This is a way of associating an interface or abstraction IMyService
with its concrete implementation MyService
. It establishes the dependency relationship within the container.
We need to build the configuration by calling the Build()
function.
Whenever we require an instance of a registered component from the container, we need to call Resolve()
function, which creates and returns an instance based on the component’s registration:
// Resolve the dependency of IMServicevar myService = container.Resolve<IMyService>();
The Resolve<>()
function will return the object of IMService
type.
In this example, we have a simple IPrinter
service that has a Print
method. In the Models
folder, we have an implementation of IPrinter
service. This example uses Autofac for dependency injection. We need to execute the following commands in the terminal:
dotnet add package Autofacdotnet run
Press the “Run” button and execute the commands above:
using System; using Autofac; namespace autofacDemo { static public class Container { public static IContainer InitContainer() { var builder = new ContainerBuilder(); builder.RegisterType<PrintSuqare>().As<IPrinter>(); builder.RegisterType<Shape>().AsSelf().InstancePerDependency(); var container = builder.Build(); return container; } } }
Let’s understand the Container.cs
code:
Line 11: We create an instance of ContainerBuilder
.
Lines 12–13: We register two components in the container: one service PrintSuqare
and second, we need to register Shape
component that depends upon IPrinter
service. Whenever we create an instance of Shape
, the container will resolve the IPrinter
service for that instance.
Line 14: We build the container
.
Line 15: We return the container
.
Let’s understand the Program.cs
code:
Lines 20–34: We have a class Shape
that depends on IPrinter
.
Line 13: We initialize the container
.
Line 14: We create Sq
object of type Shape
. Because we have registered our services and components to container
, so we use container.Resove<>()
function to resolve the dependency.
Autofac simplifies dependency injection in C# applications, promoting modular, testable, and maintainable code. By understanding the basics of Autofac and exploring its advanced features, we can leverage its power to enhance the architecture of our projects.
Free Resources