ASP.NET Core中的Ioc——Autofac

  1. ASP.NET Core中自带的IOC容器是属于轻量级的,功能并不是很多,只是提供了基础功能而已(默认采用了构造函数注入的方式,不支持属性注入,不支持AOP),它的注入服务的生命周期有3种:
    1. AddTransient:瞬时,服务在每次请求时被创建;
    2. AddScoped:作用域,服务在每次请求时被创建,生命周期横贯整次请求
    3. AddSingleton:单例,服务在第一次请求时被创建(或者当我们在ConfigureServices中指定创建某一实例并运行方法),其后的每次请求将沿用已创建服务
public void ConfigureServices(IServiceCollection services)
	    {
			services.AddTransient<ITestService1, TestService1>();//瞬时
			services.AddScoped<ITestService2, TestService2>();//作用域
			services.AddSingleton<ITestService3, TestService3>();//单例
	    }
  • 之后再控制器里,用构造函数注入
    public class HomeController : Controller
    {
        private readonly ITestService1 _testService1;
        private readonly ITestService2 _testService2;
        private readonly ITestService3 _testService3;

        public HomeController(ITestService1 testService1, ITestService2 testService2, ITestService3 testService3)
        {
            _testService1 = testService1;
            _testService2 = testService2;
            _testService3 = testService3;
        }
    }    
  1. Autofac:第三方Ioc容器Autofac的使用,支持属性注入,支持AOP等,其步骤如下:
    1. NuGet安装2个程序包:Autofac、Autofac.Extensions.DependencyInjection;
    2. Autofac在ASP.Net Core3.0以后,集成方式有所调整,在ASP.Net Core2中我们一般是把Startup的ConfigureServices方法返回值类型改为IServiceProvider,会报错:ConfigureServices returning an System.IServiceProvider isn’t supported,以下是针对ASP.Net Core3.0的修改;
    3. 修改Program,增加UseServiceProviderFactory(new AutofacServiceProviderFactory())
public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            	//改用Autofac来实现依赖注入
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
  1. 注册服务,修改Startup
    public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(o => o.EnableEndpointRouting = false);
			//注册服务(注册依赖)
          	services.AddTransient<Interface1, TestService1>();//瞬时
            services.AddSingleton<Interface2, TestService2>();//单例
            services.AddScoped<Interface3, TestService3>();//作用域
        }    

第4步,注册服务,还有另一种处理方式,即把注册服务独立出来:

	//注册服务独立出来,新增一个类,继承 Autofac.Module
    public class CustomAutofacModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
        	//注册服务
            builder.RegisterType(typeof(Service1)).As<Interface1>().SingleInstance();//单例
            builder.RegisterType(typeof(Service2)).As<Interface2>().InstancePerLifetimeScope();//线程独立
            builder.RegisterType(typeof(Service3)).As<Interface3>().InstancePerDependency();//瞬时,为每个依赖或者调用(Resolve())都创建一个新的对象
        }
    }

Startup里就不用注册服务了,在ConfigureServices下面,新增一个ConfigureContainer方法

        // 注册服务独立出来
        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterModule(new CustomAutofacModule());
        }
  1. 以上Autofac配置完成了,最后在控制器里调用,利用控制器的构造函数注入
    public class HomeController : Controller
    {
        private readonly Interface1 _Service1;
        private readonly Interface2 _Service2;
        private readonly Interface3 _Service3;

        public HomeController(Interface1 s1, Interface2 s2, Interface3 s3)
        {
            //依赖注入
            _Service1 = s1;
            _Service2 = s2;
            _Service3 = s3;
        }
        public IActionResult Index()
        {
            _Service1.Show();
            _Service2.Show();
            _Service3.Show();

            return View();
        }
    }

6.补充说明,可以使用批量注册方法:
在这里插入图片描述

//批量注册
    public class AutofacModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            string basePath = AppContext.BaseDirectory;
            var assembly = Assembly.LoadFrom(Path.Combine(basePath, "AspNetCore.Service.dll"));
            builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();
        }
    }
  1. 补充说明:
    1. builder.RegisterType<A>().AsImplementedInterfaces();,以接口方式进行注入,使用时用IA,会返回一个A的实例,即将自身的实例进行注入;
    2. builder.RegisterType<A>().AsImplementedInterfaces().InstancePerRequest() ; 每次请求共享同一个实例,使用ef时,使不同的操作使用同一个数据上下文;
    3. builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())注册了当前程序集内的所有的类;
    4. InstancePerHttpRequest在一次Http请求上下文中,共享一个组件实例。仅适用于asp.net mvc开发

参考文档:ASP.NET Core依赖注入&AutoFac
Autofac在ASP.Net Core3.0配置
.net core2.1 三层中使用Autofac代替原来Ioc
关于依赖注入autofac的相关知识

原文地址:https://www.cnblogs.com/zoulei0718/p/14315570.html