How to use Autofac in C#

By FoxLearn 5/22/2024 3:05:37 AM   17.08K
Using dependency injection (DI) container for .NET applications using Autofac in C#

What is autofac c#

Autofac is a popular dependency injection (DI) container for .NET applications. It's an addictive IoC (Inversion of Control) container for .NET Core, ASP.NET Core, .NET 4.5.1+, Universal Windows apps, and more. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity.

Here's a basic guide on how to use Autofac in a C# project:

First off, You can create a new console project called AutofacDemo

Next, Right click on your project select Manage NuGet Packages -> Search autofac -> install

c# install autofac

You can install it by running the following command in the NuGet Package Manager Console or terminal:

Install-Package Autofac

or

dotnet add package Autofac

After you finish installing the library, you can create an interface called IConnection

public interface IConnection
{
    void Connect();
    void Command(string command);
}

Create MySqlConnection inherit from IConnection, then implement Command, Connect methods as shown below.

public class MySqlConnection : IConnection
{
    public void Command(string command)
    {
        Console.Write("Execute MySql command: {0}", command);
    }

    public void Connect()
    {
        Console.WriteLine("Connect to MySql Server...");
    }
}

Similarly, create SqlConnection inherit from IConnection

public class SqlConnection : IConnection
{
    public void Command(string command)
    {
        Console.Write("Execute Sql command: {0}", command);
    }

    public void Connect()
    {
        Console.WriteLine("Connect to Sql Server...");
    }
}

Autofac uses a container to manage the dependency injection. You need to set up the container by registering your dependencies by creating an AppService class to manage the instance you want to create

public static class AppService
{
    static IContainer Container { get; set; }
    static AppService()
    {
        ContainerBuilder builder = new ContainerBuilder();
        // Register types
        builder.RegisterType<MySqlConnection>().As<IConnection>();//Change your instance you want to create
        // Build the container
        Container = builder.Build();
    }

    // Resolve dependencies
    public static IConnection Connection => Container.Resolve<IConnection>();
}

You can call Connect, Command method in Main method

class Program
{
    static void Main(string[] args)
    {
        // Use the service
        AppService.Connection.Connect();
        AppService.Connection.Command("Insert");
        Console.ReadLine();//Wait
    }
}

In this example, SqlConnection is a class that implements the IConnection interface. Autofac will handle the instantiation and injection of dependencies when IConnection is requested.

Once the container is set up, you can use dependency injection to resolve instances of registered types. Autofac provides several ways to inject dependencies:

  • Constructor Injection: Dependencies are injected via the constructor of the consuming class.
  • Property Injection: Dependencies are injected via public properties of the consuming class.
  • Method Injection: Dependencies are injected via methods of the consuming class.

Here's an example of constructor injection:

public class MyClass
{
    private readonly IConnection _connection;

    public MyClass(IConnection connection)
    {
        _connection = connection;
    }

    public void DoSomething()
    {
        _connection.Connect();
    }
}

Autofac supports various lifetime scopes for registered components, such as singleton, instance per dependency, and instance per request. You can specify the lifetime scope when registering components using methods like SingleInstance(), InstancePerLifetimeScope(), and InstancePerDependency().

Here's an example of registering a component with a singleton lifetime scope:

builder.RegisterType<MySingleton>().As<IMySingleton>().SingleInstance();

The MySingleton will be created once and shared across all consumers throughout the lifetime of the application.

Autofac offers advanced features such as named and keyed services, property injection, modules for organizing registrations, and interception for aspect-oriented programming.

You can easily to change the instance you want to create, we don't need to change code in the Main method.

builder.RegisterType<SqlConnection>().As<IConnection>();//Change your instance you want to create

Press F5 to run your program

c# autofac

Autofac simplifies dependency management and promotes loosely coupled and testable code in your C# applications.