IOC ------- inversion of control
Since all containers to be managed, natural container can manage the life cycle of the object, as well as AOP (some logic at the time of implantation)
.Net Core built an IOC container, in ServiceCollection, there are three life cycle
AddTransient ----- instantaneous, with the most
AddScoped ----- only one instance of a request
AddSingleton ----- only one instance of a thread
But ServiceCollection has limitations: You can not batch injection, can not achieve AOP.
Solution: use third-party IOC container, such as Atuofac
Step1: introducing two assemblies Autofac.Extras.DynamicProxy (Autofac the dynamic proxy, it relies Autofac, can be incorporated without Autofac separately) , Autofac.Extensions.DependencyInjection (Autofac extension)
Step2: replace the old container in the Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
Step3: Adding ConfigureContainer method in Startup.cs
public void ConfigureContainer (ContainerBuilder containerBuilder) { var assemblyFiles the Assembly.LoadFrom = ( " filePathName " ); // specifies the type of scanner register set provides all interfaces to its implementation. containerBuilder.RegisterAssemblyTypes (assemblyFiles) .AsImplementedInterfaces (); }