/// <summary> /// Loads all the bean information by the given configuration class. /// </summary> /// <param name="configType">Configuration class.</param> private void LoadConfigurationClass(Type configType) { if (configurationInstances.ContainsKey(configType)) { return; // Already loaded. } configType .GetMethods() .ToList() .ForEach(x => { BeanAttribute beanAttr = x.GetCustomAttribute <BeanAttribute>(); PrimaryAttribute primaryAttr = x.GetCustomAttribute <PrimaryAttribute>(); if (beanAttr == null) { return; } if (!beanInfo.ContainsKey(x.ReturnType)) { beanInfo.Add(x.ReturnType, new TypeContainer(this, x.ReturnType)); } string beanName = beanAttr.Name ?? x.Name; beanInfo[x.ReturnType].AddBean(beanName, x, primaryAttr != null, beanAttr.InitMethod); }); object configInstance = Activator.CreateInstance(configType); configurationInstances.Add(configType, configInstance); // TODO: Add beans declared as properties. }
ApplyAsImplementedInterfaces <TLimit>( this IRegistrationBuilder <TLimit, SimpleActivatorData, SingleRegistrationStyle> builder, BeanAttribute attr, Type type) { if (attr.AsImplementedInterfaces) { builder = builder.As(GetImplementedInterfaces(type)); } return(builder); }
ApplyAsSelf <TLimit>( this IRegistrationBuilder <TLimit, SimpleActivatorData, SingleRegistrationStyle> builder, BeanAttribute attr, Type type) { if (attr.AsSelf) { builder = builder.As(type); } return(builder); }
public static void ResolveBeansForClass(object obj) { var props = obj.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(BeanAttribute))); foreach (PropertyInfo property in props) { BeanAttribute attribute = (BeanAttribute)property.GetCustomAttribute(typeof(BeanAttribute)); string beanId = attribute.id; property.SetValue(obj, Services.Instance.GetBean <object>(beanId)); } }
/// <summary> /// 注册到autofac /// </summary> /// <param name="builder"></param> /// <param name="fromType"></param> /// <param name="bean"></param> public static void BindBuildWithScope(this ContainerBuilder builder, Type fromType, BeanAttribute bean) { AutofacScope scope = bean.AutofacScope; Type toType = bean.As; string name = bean.Named; var registrar = builder.RegisterType(fromType); switch (scope) { case AutofacScope.SingleInstance: if (toType == null) { if (!string.IsNullOrEmpty(name)) { registrar.Named(name, fromType).SingleInstance().PropertiesByAttributeAutowired(); } else { registrar.SingleInstance().PropertiesByAttributeAutowired(); } } else { if (!string.IsNullOrEmpty(name)) { registrar.As(toType).Named(name, toType).SingleInstance().PropertiesByAttributeAutowired(); } else { registrar.As(toType).SingleInstance().PropertiesByAttributeAutowired(); } } break; case AutofacScope.InstancePerDependency: if (toType == null) { if (!string.IsNullOrEmpty(name)) { registrar.Named(name, fromType).InstancePerDependency().PropertiesByAttributeAutowired(); } else { registrar.InstancePerDependency().PropertiesByAttributeAutowired(); } } else { if (!string.IsNullOrEmpty(name)) { registrar.As(toType).Named(name, toType).InstancePerDependency().PropertiesByAttributeAutowired(); } else { registrar.As(toType).InstancePerDependency().PropertiesByAttributeAutowired(); } } break; case AutofacScope.InstancePerOwned: if (toType == null) { if (!string.IsNullOrEmpty(name)) { registrar.Named(name, fromType).InstancePerLifetimeScope().PropertiesByAttributeAutowired(); } else { registrar.InstancePerLifetimeScope().PropertiesByAttributeAutowired(); } } else { if (!string.IsNullOrEmpty(name)) { registrar.As(toType).Named(name, toType).InstancePerOwned(toType).PropertiesByAttributeAutowired(); } else { registrar.As(toType).InstancePerOwned(toType).PropertiesByAttributeAutowired(); } } break; case AutofacScope.InstancePerRequest: if (toType == null) { if (!string.IsNullOrEmpty(name)) { registrar.Named(name, fromType).InstancePerRequest().PropertiesByAttributeAutowired(); } else { registrar.InstancePerRequest().PropertiesByAttributeAutowired(); } } else { if (!string.IsNullOrEmpty(name)) { registrar.As(toType).Named(name, toType).InstancePerRequest().PropertiesByAttributeAutowired(); } else { registrar.As(toType).InstancePerRequest().PropertiesByAttributeAutowired(); } } break; case AutofacScope.InstancePerLifetimeScope: if (toType == null) { if (!string.IsNullOrEmpty(name)) { registrar.Named(name, fromType).InstancePerLifetimeScope().PropertiesByAttributeAutowired(); } else { registrar.InstancePerLifetimeScope().PropertiesByAttributeAutowired(); } } else { if (!string.IsNullOrEmpty(name)) { registrar.As(toType).Named(name, toType).InstancePerLifetimeScope().PropertiesByAttributeAutowired(); } else { registrar.As(toType).InstancePerLifetimeScope().PropertiesByAttributeAutowired(); } } break; case AutofacScope.InstancePerMatchingLifetimeScope: if (toType == null) { if (!string.IsNullOrEmpty(name)) { registrar.Named(name, fromType).InstancePerMatchingLifetimeScope().PropertiesByAttributeAutowired(); } else { registrar.InstancePerMatchingLifetimeScope().PropertiesByAttributeAutowired(); } } else { if (!string.IsNullOrEmpty(name)) { registrar.As(toType).Named(name, toType).InstancePerMatchingLifetimeScope().PropertiesByAttributeAutowired(); } else { registrar.As(toType).InstancePerMatchingLifetimeScope().PropertiesByAttributeAutowired(); } } break; } if (bean.InterceptorType != null) { try { registrar.EnableInterfaceInterceptors().InterceptedBy(bean.InterceptorType); } catch (Exception) { }; } if (string.IsNullOrEmpty(name)) { //默认使用类的名字注册 var newBean = bean.Clone(); newBean.Named = fromType.Name; BindBuildWithScope(builder, fromType, newBean); } }
/// <summary> /// 扫描Bean特性的方法,并创建实例。 /// </summary> /// <param name="dlls">指定的要被扫描的dll。</param> private void ScanBeanAttribute(string[] dlls) { foreach (string dll in dlls) { Assembly assembly = Assembly.LoadFile(dll); Type[] types = assembly.GetTypes(); foreach (Type clazz in types) { if (clazz.IsClass) { //1.扫描类的Configuration特性 //获取属性 Attribute attributeConfigurationAttribute = clazz.GetCustomAttribute(typeof(ConfigurationAttribute)); if (attributeConfigurationAttribute == null)//如果该类没有Configuration特性 { continue; } ConfigurationAttribute configurationAttribute = (ConfigurationAttribute)attributeConfigurationAttribute; string beanName = clazz.Name.Substring(0, 1).ToLower() + (clazz.Name.Length > 1 ? clazz.Name.Substring(1) : string.Empty); if (!string.IsNullOrWhiteSpace(configurationAttribute.Name)) { beanName = configurationAttribute.Name; } bool isDefault = true;//是否使用默认配置文件 PropertiesUtil _properties = null; string configurationPath = "application.properties"; if (!string.IsNullOrWhiteSpace(configurationAttribute.Path))//如果设置了ConfigurationAttribute的Path值 { configurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configurationAttribute.Path); _properties = new PropertiesUtil(configurationPath); isDefault = false; } //2.扫描字段的Value特性 FieldInfo[] fieldInfos = clazz.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fieldInfos) { Attribute attributeValueAttribute = fieldInfo.GetCustomAttribute(typeof(ValueAttribute)); if (attributeValueAttribute == null)//如果此字段没有Value特性 { continue; } ValueAttribute valueAttribute = (ValueAttribute)attributeValueAttribute; string valueName = fieldInfo.Name; //字段名称 if (!string.IsNullOrWhiteSpace(valueName)) //如果设置了ValueAttribute的Key值 { valueName = valueAttribute.Key; } if (BeanContainer.ContainsKey(beanName)) { if (isDefault == false)//如果使用的不是默认配置文件 { fieldInfo.SetValue(BeanContainer[beanName].Bean, Convert.ChangeType(_properties[valueName], fieldInfo.FieldType)); } else { fieldInfo.SetValue(BeanContainer[beanName].Bean, Convert.ChangeType(Properties[valueName], fieldInfo.FieldType)); } } } //3.扫描方法的Bean特性 MethodInfo[] methods = clazz.GetMethods(); foreach (MethodInfo method in methods) { Attribute attributeBeanAttribute = method.GetCustomAttribute(typeof(BeanAttribute)); if (attributeBeanAttribute == null)//如果此方法没有Bean特性 { continue; } BeanAttribute beanAttribute = (BeanAttribute)attributeBeanAttribute; string methodName = method.Name; //方法名称 if (!string.IsNullOrWhiteSpace(beanAttribute.Name)) //如果设置了BeanAttribute的Name值 { methodName = beanAttribute.Name; } if ("Void".Equals(method.ReturnType.Name))//如果此方法无返回值 { throw new BeanCreationException(string.Format("创建名为‘{0}’的bean错误。方法需要返回值。", methodName)); } if (BeanContainer.ContainsKey(beanAttribute.Name))//判断单例容器里是否已存在 { throw new BeanCreationException(string.Format("创建名为‘{0}’的bean错误。已经存在名为‘{1}’的实例。", methodName, methodName)); } //4.扫描方法参数的Parameter特性 ParameterInfo[] parameterInfos = method.GetParameters(); int parameterCount = parameterInfos.Length; if (parameterCount > 0)//如果有参数 { object[] parameterValues = new object[parameterCount]; int index = 0; foreach (ParameterInfo parameterInfo in parameterInfos)//设置参数的值 { Attribute attributeParameterAttribute = parameterInfo.GetCustomAttribute(typeof(ParameterAttribute)); string parameterName = parameterInfo.Name; //默认参数的名称 if (attributeParameterAttribute != null) //如果有特性标注 { ParameterAttribute parameterAttribute = (ParameterAttribute)attributeParameterAttribute; parameterName = parameterAttribute.Name; } if (!BeanContainer.ContainsKey(parameterName)) //如果从容器中找不到参数的实例 { if (parameterInfo.HasDefaultValue) //根据参数是否设置了默认值来决定是否抛出异常 { parameterValues[index] = parameterInfo.DefaultValue; continue; } throw new BeanNotFoundException(string.Format("找不到指定的实例‘{0}’。", parameterName)); } parameterValues[index] = BeanContainer[parameterName].Bean; index++; } if (BeanContainer.ContainsKey(beanName)) { //执行方法,得到方法的返回值,并存入单例容器 object objReturn = method.Invoke(BeanContainer[beanName].Bean, parameterValues); BeanContainer.Add(methodName, new BeanInfo() { Bean = objReturn, AtrributeType = AtrributeType.Bean }); } } else//如果无参数 { if (BeanContainer.ContainsKey(beanName)) { //执行方法,得到方法的返回值,并存入单例容器 object objReturn = method.Invoke(BeanContainer[beanName].Bean, null); BeanContainer.Add(methodName, new BeanInfo() { Bean = objReturn, AtrributeType = AtrributeType.Bean }); } } } //end : foreach (MethodInfo method in methods) } //end : if (clazz.IsClass) } //end : foreach (Type clazz in types) } //end : foreach (string dll in dlls) }