AutoFac--属性注入
AutoFac 属性注入需要改两个位置
1、用Autofac进行注入,对全部控制器进行 属性注入:Autofac中通过对ControllerFeature中的Controller进行IOC注册,并使用PropertiesAutowired开启属性注入。
#region 对Controller类型注册 批量 var manager = new ApplicationPartManager(); manager.ApplicationParts.Add(new AssemblyPart(assembly:System.Reflection.Assembly.GetExecutingAssembly())); manager.FeatureProviders.Add(new ControllerFeatureProvider()); var feature = new ControllerFeature(); manager.PopulateFeature(feature: feature); builder.RegisterTypes(feature.Controllers.Select(n => n.AsType()).ToArray()).PropertiesAutowired(); #endregion //标识单个controller 可以使用属性注入 // builder.RegisterType对Controller注册().PropertiesAutowired();
这部分代码需要引入:
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;
以上代码写在public class AutofacMoule : Module 中 参考:
2、(重要)修改默认的Controller创建者,使用Autofac的ServiceProvider完成Controller的创建工作。
Startup文件中ConfigureServices函数:需要在AddControllers 或者AddMvc前添加代码:
services.Replace(ServiceDescriptor.Transient
这行代码需要引用:
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Mvc.Controllers;
3、Controller使用:
使用构造注入时 定了了变量
public IUserService _userservice;
改为属性注入后,就是
public IUserService _userservice { get; set; }
同时,构造函数也不需要引入IUserService 了(我的测试代码比较乱,看个大概就行)
在getuserByid 函数中正常使用就可以了。
参考: