使用Autofac替换掉微软的DI

本文的项目为ASP.NET Core3.1,传统三层架构 在这就不过多介绍Autofac,直接上代码

Autofac官网:https://autofac.org/

ASP.NET Core使用Autofac_asp.net

Program.cs的 IHostBuilder 方法内加上 .UseServiceProviderFactory(new AutofacServiceProviderFactory())(如下图)

ASP.NET Core使用Autofac_程序集_02

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
             .UseServiceProviderFactory(new AutofacServiceProviderFactory())//启用autofac容器
            .ConfigureWebHostDefaults(webBuilder =>
            {
              webBuilder.UseStartup<Startup>();
            });
  }

在Startup.cs内新增 ConfigureContainer 方法
属性介绍
RegisterAssemblyTypes:寄存器程序集类型
AsImplementedInterfaces:实现的接口
InstancePerDependency:实例依赖关系
PropertiesAutowired:属性自动连接
ASP.NET Core使用Autofac_命名空间_03

        /// <summary>
        /// 配置Autofac容器替换微软的DI
        /// </summary>
        /// <param name="builder"></param>
        public void ConfigureContainer(ContainerBuilder builder)
        {
            var basePath = AppContext.BaseDirectory;
            //DALService所在程序集命名空间
            string DALPath = Path.Combine(basePath, "GraduationProject.DAL.dll");
            Assembly DAL = Assembly.LoadFrom(DALPath);
            //BLLService所在程序集命名空间
            string BLLPath = Path.Combine(basePath, "GraduationProject.BLL.dll");
            Assembly BLL = Assembly.LoadFrom(BLLPath);

            builder.RegisterAssemblyTypes(DAL).InstancePerDependency().PropertiesAutowired();
            builder.RegisterAssemblyTypes(BLL).AsImplementedInterfaces().InstancePerDependency().PropertiesAutowired();
        }