Autofac属性方法注入
添加Autofac和Autofac.Extensions.DependencyInjection包
使用autofac替换内部IOC
.UseServiceProviderFactory(new AutofacServiceProviderFactory());
public interface ICompanyService { public int GetId(int id); } public interface ISysUserService { public int GetId(int id); } public class CompanyService : ICompanyService { /// <summary> /// 这里是一个属性:如果支持属性注入---CompanyService构造完成以后,要吧这个属性的实例构建出来; /// </summary> [CustomProperty] public ISysUserService _ISysUserService { get; set; } public ISysUserService _ISysUserServiceNoAttribute { get; set; } public ISysUserService _ISysUserServiceCtor = null; public CompanyService(ISysUserService iSysUserService) { _ISysUserServiceCtor = iSysUserService; } public ISysUserService _ISysUserServiceMethod = null; public void SetService(ISysUserService iSysUserService) { _ISysUserServiceMethod = iSysUserService; } public int GetId(int id) { return id; } } public class SysUserService : ISysUserService { public SysUserService() { Console.WriteLine($"{GetType().Name}被构造。。。。"); } public int GetId(int id) { return 1; } } //添加属性注入时使用的属性 [AttributeUsage(AttributeTargets.Property)]//为了支持属性注入,只能标记在属性上 public class CustomPropertyAttribute : Attribute { } /// <summary> /// IPropertySelector:查看 属性上是否标记某一个特性 /// </summary> public class CustomPropertySelector : IPropertySelector { public bool InjectProperty(PropertyInfo propertyInfo, object instance) { //需要一个判断的维度; 如果标记的有CustomPropertyAttribute特性 返回True:返回true;就构造实例 return propertyInfo.CustomAttributes.Any(it => it.AttributeType == typeof(CustomPropertyAttribute)); } } 注册服务 public void ConfigureContainer(ContainerBuilder containerBuilder) { //如果要注册某一个Dll中的服务;可以通过反射把dll加载进来;然后再读取出来抽象和具体;然后逐个注册进去; //注册服务 containerBuilder.RegisterType<CompanyService>() .OnActivated(e => e.Instance.SetService(e.Context.Resolve<ISysUserService>())) //方法注入--再获取实例后,把指定的某一个方法给执行以下 .As<ICompanyService>() .PropertiesAutowired(new CustomPropertySelector()); //Autoafc自己来调用的这个方法 containerBuilder.RegisterType<SysUserService>().As<ISysUserService>(); }