Exemple #1
0
        private static ComponentAttribute ComponentDynamic(this Type component)
        {
            // The dynamic version is necessary when the component type was obtained using the type service
            foreach (var attribute in component.GetCustomAttributes(true))
            {
                if (IsComponentMetadata(attribute.GetType()))
                {
                    var componentAttribute = new ComponentAttribute();

                    foreach (var property in attribute.GetType().GetProperties(
                                 BindingFlags.Instance |
                                 BindingFlags.Public |
                                 BindingFlags.GetProperty |
                                 BindingFlags.SetProperty))
                    {
                        var componentAttributeProperty = componentAttribute.GetType().GetProperty(property.Name);
                        if (componentAttributeProperty != null && componentAttributeProperty.CanWrite)
                        {
                            componentAttributeProperty.SetValue(componentAttribute, property.GetValue(attribute, null), null);
                        }
                    }

                    return(componentAttribute);
                }
            }

            return(null);
        }
Exemple #2
0
        /// <summary>
        /// 注册PropertySource
        /// </summary>
        /// <param name="component"></param>
        /// <param name="configuration"></param>
        private static void RegisterPropetySources(ComponentAttribute component, IConfiguration configuration, IServiceCollection services)
        {
            if (!typeof(PropertySourceAttribute).IsAssignableFrom(component.GetType()))
            {
                return;
            }
            var propertySource     = component as PropertySourceAttribute;
            var implementationType = propertySource.ImplementationType;

            if (propertySource != null)
            {
                if (string.IsNullOrWhiteSpace(propertySource.Name))
                {
                    propertySource.Name = propertySource.ImplementationType.Name; // 默认使用类名称作为配置节点Key.
                }
                var section = configuration.GetSection(propertySource.Name);

                if (!section.Exists() && !propertySource.IgnoreResourceNotFound)
                {
                    throw new ArgumentNullException($"PropertySource:{propertySource.Name}");
                }

                var instance = Activator.CreateInstance(implementationType);
                configuration.Bind(propertySource.Name, instance);

                component.Instance = instance;
            }
        }