Autofac (dependency injection container) in. NET

Autofac concept

Autofac is an IOC container. Many beginners don't understand IOC and DI.
Brief summary:

  1. IOC: instead of creating / new the instance, the user gives it to the container to create (AutoFac acts as the container here). This is the process of controlling inversion to obtain dependent objects is reversed. Originally, you took the initiative to do some operations, but now some operations force you to do them.
  2. DI: the process of injecting (usually through reflection) the caller after the instance created by the container is dependency injection (such as attribute injection, constructor injection, etc.).

Use of Autofac

A simple little Demo

  1. Open Visual Studio. I use 2022 to create a console application

    I use. Net version 6.0 here

    2. Create a new class
 /// <summary>
        ///Define an interface for outputting information and a Write method with a parameter of string type and no return value. At this time, you don't need to care about the specific operation of the method
        /// </summary>
        public interface IExport
            void Write(string content);
        /// <summary>
        ///To implement the Write method in the interface, there is only one method and a de method is required
        /// </summary>
        public class ConsoleIExport : IExport {
            public void Write(string content) => Console.WriteLine(content);
        public interface IExportDate {
            void WriteDate();
    /// <summary>
    ///At this time, we need to make WriteDate depend on the class ConsoleIExport, and define IExport
    /// </summary>
    public class ConsoleIExportDate : IExportDate
        private IExport Export;
        public ConsoleIExportDate(IExport export)
            this.Export = export;
        public void WriteDate() => this.Export.Write(DateTime.Now.ToString());
        //Now that we have a reasonably structured (if artificial) dependency set, let's add Autofac!

At this time, NuGet package needs to be introduced, and intelligent prompts can be provided in. NET6.

3. Register components

/// <summary>
    ///Register components
    /// </summary>
    public class ExecAutofac
        //Create ContainerBuilder and register components in it
           ContainerBuilder builder = new();
        private static IContainer? Container { get; set; }
        public ExecAutofac() {
        Container = builder.Build();
        //After registration, we call
        public static void Begin()
            using var scope = Container.BeginLifetimeScope();
            var writer = scope.Resolve<IExportDate>();

Finally, call our constructor ExecAutofac to OK.

// See for more information
using Autofac;
ExecAutofac  exec = new();

We can see that the program has output our time.


The WriteDate method creates a lifecycle scope from which dependencies can be resolved. This is done to avoid any memory leaks - if IExport or its dependencies are one-time, they will be released automatically when the scope is released.
The WriteDate method IExport resolves manually from the lifecycle scope. (this is the "service location".) inside
Autofac sees that IExportDate is mapped to console IExportDate, so it starts to create a console IExportDate
Autofac believes that an IExport is required for ConsoleIExportDate in its constructor. (this is constructor injection.)
Autofac sees that IExport maps to ConsoleIExport, so it creates a new instance of ConsoleIExport.
Autofac uses the new ConsoleIExport instance to complete the build of the ConsoleIExportDate
Autofac returns the fully constructed ExecAutofac for Begin consumption.
Call writer.WriteDate(), IExportDate.WriteDate(), because this is the problem to be solved.
Autofac lifecycle scope released. Any one-off items resolved within this life cycle will also be disposed of.

BeginLifetimeScope()Start the lifecycle of the container
RegisterType()The type registered with the container can be either an interface or a base class
Resolve()Inspection Service

This will produce a flowchart.:

  • Let's talk about the use of Autofac. If you don't know much about it, you can baidu by yourself.

Tags: C# .NET Container ioc Autofac

Posted on Thu, 14 Oct 2021 02:34:32 -0400 by pjoshi