. NET6 - Autofac

The protagonist of this article is Autofac, which is a very nice dependency injection framework. For the time being, let's share some terms: DI (dependency injection), IOC (control inversion) and IOC container.

Know these nouns through Demo

Demo is very simple. Create an ASP Net core project, add a new UserService class, which is called in the WeatherForecastController class created by default.

The user service class (UserService) adds a simple GetUser method

 public class UserService

        public virtual string GetUser() 
            Console.WriteLine("implement GetUser method");
            return "Get a user information";

Weather forecast (WeatherForecastController) controller class call

If the get method of the weather forecast controller class calls the getUser method of UserService, first create an instance of UserService class through new to complete the call.

private readonly UserService _userService = new UserService();

Then we can say that the weather forecast class depends on the user service class, so the code implementation is no problem. According to the software design principle, try to rely on the interface rather than the specific implementation.

Next, create an interface class (iuserice)

public interface IUserSerice
        string GetUser();

After the interface is replaced, the instantiated code is as follows

private readonly IUserSerice _userService = new UserService();

We found that the weather forecast class depends on the user service class. The instantiation code of the user service class is in the weather forecast class. The instance creation control is in the caller. In software design, we often say that it is high cohesion and low coupling. How to further decouple it? Hand over the control of instance creation, which is the idea of control flip (IOC). To whom? It's like a black box. It's an IOC container NETcore framework has built-in IOC container framework. Of course, we can also use the third-party autofac framework. The whole life cycle of instance creation and destruction is handed over to the container. How to obtain the instance object? We can inject the object we depend on through constructor, attribute and method tag [FromServices] through injection. This process is called dependency injection (DI).

I'll throw a brick to attract jade. I can share better opinions in the message area^_^

The function of Autofac is also a part that attracts me

  1. Rich registration (configuration of service components and implementations): ① RegisterType, ② RegisterAssemblyTypes, ③ Autofac Module
  2. Injection method: ① constructor, ② attribute
  3. Life cycle: ① instantaneous, ② single case, ③ range
  4. Support AOP (aspect oriented programming)

Autofac and ASP Net 6 integration rewrite the above Demo

1. Install nuget package: Autofac Extensions. DependencyInjection

2. In program Configuration in CS class

//Replace the built-in ServiceProviderFactory
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>

Call the weather forecast, 3

private readonly ILogger<WeatherForecastController> _logger;
        private readonly IUserSerice userService;  
        public WeatherForecastController(ILogger<WeatherForecastController> logger
            , IUserSerice userService)
            _logger = logger;        
            this.userService = userService;


   [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]

Operation results

Refer to the official website: https://autofac.readthedocs.io/en/latest/index.html

Posted by xadmin on Mon, 16 May 2022 10:16:57 +0300