.net Core WebApi使用AutoFac

1.在要添加的项目中选中 依赖项->右键->管理NuGet程序包(N)

.net Core WebApi使用AutoFac

 

 2.在NuGet包管理器中输入Autofac,安装选中文件

.net Core WebApi使用AutoFac

 

 3.在项目中找到Program.cs文件,添加如下代码

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                // 添加依赖注入
                .UseServiceProviderFactory(new AutofacServiceProviderFactory());

 

.net Core WebApi使用AutoFac

 

 4.在项目中找到Startup.cs文件,添加如下代码

        /// <summary>
        /// 依赖注入配置容器
        /// </summary>
        /// <param name="builder"></param>
        public void ConfigureContainer(ContainerBuilder builder)
        {
            ////单个服务注入
            //builder.RegisterType<OrderService>().As<IOrderService>();

            // 获取 Service.dll 程序集服务,并注册
            var assemblysService = Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, "NetCoreWebApi.Service.dll"));
            // 获取 IService.dll 程序集服务,并注册
            var assemblysIService = Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, "NetCoreWebApi.IService.dll"));
            builder.RegisterAssemblyTypes(assemblysService)
                   .AsImplementedInterfaces()
                   .InstancePerDependency().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
            builder.RegisterAssemblyTypes(assemblysIService)
                   .AsImplementedInterfaces()
                   .InstancePerDependency().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
        }

 

.net Core WebApi使用AutoFac

 

 5.添加好依赖注入,就可以直接在项目中使用

        private readonly ISysRoleServices _sysRoleServices;
        public SysRoleController(ISysRoleServices sysRoleServices)
        {
            _sysRoleServices = sysRoleServices;
        }

 

.net Core WebApi使用AutoFac

 

 .net Core WebApi使用AutoFac

 

上一篇:ASP.NET Core WebApi基于JWT实现接口授权验证


下一篇:Net项目添加 WebAPI