public void ChangeToCompatibleType_LooksForTryParseMethod() { var address = "127.0.0.1"; var value = TypeManipulation.ChangeToCompatibleType(address, typeof(IPAddress)); Assert.Equal(value, IPAddress.Parse(address)); }
/// <summary> /// Converts configured parameter values into parameters that can be used /// during object resolution. /// </summary> /// <param name="configuration"> /// The <see cref="IConfiguration"/> element that contains the component /// with defined parameters. /// </param> /// <param name="key"> /// The <see cref="String"/> key indicating the sub-element with the /// parameters. Usually this is <c>parameters</c>. /// </param> /// <returns> /// An <see cref="IEnumerable{T}"/> of <see cref="Parameter"/> values /// that can be used during object resolution. /// </returns> public static IEnumerable <Parameter> GetParameters(this IConfiguration configuration, string key) { if (configuration == null) { throw new ArgumentNullException("configuration"); } if (key == null) { throw new ArgumentNullException("key"); } if (String.IsNullOrWhiteSpace(key)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, ConfigurationResources.ArgumentMayNotBeEmpty, "configuration key"), "key"); } foreach (var parameterElement in configuration.GetSection(key).GetChildren()) { var parameterValue = GetConfiguredParameterValue(parameterElement); var parameterName = GetKeyName(parameterElement.Key); yield return(new ResolvedParameter( (pi, c) => String.Equals(pi.Name, parameterName, StringComparison.OrdinalIgnoreCase), (pi, c) => TypeManipulation.ChangeToCompatibleType(parameterValue, pi.ParameterType, pi))); } }
/// <summary> /// 对于memberInfo 或者 parameterInfo 进行设值 /// </summary> /// <param name="classType"></param> /// <param name="memberType"></param> /// <param name="memberInfo"></param> /// <param name="parameterInfo"></param> /// <returns></returns> private object Resolve(Type classType, Type memberType, MemberInfo memberInfo, ParameterInfo parameterInfo = null) { if (classType == null) { return(null); } if (string.IsNullOrEmpty(this.value)) { return(null); } try { if (!this.value.StartsWith("#{") || !this.value.EndsWith("}")) { var parameterValue = this.value; var parseValue = parameterInfo == null ? TypeManipulation.ChangeToCompatibleType(parameterValue, memberType, memberInfo) : TypeManipulation.ChangeToCompatibleType(parameterValue, memberType, parameterInfo); return(parseValue); } else { var key = this.value.Substring(2, this.value.Length - 3)?.Trim(); if (AutofacAnnotationModule.ComponentModelCache.TryGetValue(classType, out var component)) { foreach (var metaSource in component.MetaSourceList) { if (metaSource.Configuration == null) { continue; } IConfigurationSection metData = metaSource.Configuration.GetSection(key); var parameterValue = ConfigurationUtil.GetConfiguredParameterValue(metData); if (parameterValue == null) { //表示key不存在 从下一个source里面去寻找 continue; } var parseValue = parameterInfo == null ? TypeManipulation.ChangeToCompatibleType(parameterValue, memberType, memberInfo) : TypeManipulation.ChangeToCompatibleType(parameterValue, memberType, parameterInfo); return(parseValue); } } } return(null); } catch (Exception ex) { throw new DependencyResolutionException($"Value set error,can not resolve class type:{classType.FullName} =====>" + $" {(parameterInfo == null?memberType.Name:parameterInfo.Name)} " + (!string.IsNullOrEmpty(this.value) ? $",with value:[{this.value}]" : ""), ex); } }
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { var instantiatableType = GetInstantiableType(destinationType); var castValue = value as DictionaryElementCollection; if (castValue != null && instantiatableType != null) { var dictionary = (IDictionary)Activator.CreateInstance(instantiatableType); Type[] generics = instantiatableType.GetGenericArguments(); foreach (var item in castValue) { if (String.IsNullOrEmpty(item.Key)) { throw new ConfigurationErrorsException("Key cannot be null in a dictionary element."); } var convertedKey = TypeManipulation.ChangeToCompatibleType(item.Key, generics[0], null); var convertedValue = TypeManipulation.ChangeToCompatibleType(item.Value, generics[1], null); dictionary.Add(convertedKey, convertedValue); } return(dictionary); } return(base.ConvertTo(context, culture, value, destinationType)); }
/// <summary> /// Converts configured property values into parameters that can be used /// during object resolution. /// </summary> /// <param name="configuration"> /// The <see cref="IConfiguration"/> element that contains the component /// with defined properties. /// </param> /// <param name="key"> /// The <see cref="String"/> key indicating the sub-element with the /// propeties. Usually this is <c>properties</c>. /// </param> /// <returns> /// An <see cref="IEnumerable{T}"/> of <see cref="Parameter"/> values /// that can be used during object resolution. /// </returns> public static IEnumerable <Parameter> GetProperties(this IConfiguration configuration, string key) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, ConfigurationResources.ArgumentMayNotBeEmpty, "configuration key"), nameof(key)); } foreach (var propertyElement in configuration.GetSection(key).GetChildren()) { var parameterValue = GetConfiguredParameterValue(propertyElement); string parameterName = GetKeyName(propertyElement.Key); yield return(new ResolvedParameter( (pi, c) => { return pi.TryGetDeclaringProperty(out PropertyInfo prop) && string.Equals(prop.Name, parameterName, StringComparison.OrdinalIgnoreCase); }, (pi, c) => { var prop = (PropertyInfo)null; pi.TryGetDeclaringProperty(out prop); return TypeManipulation.ChangeToCompatibleType(parameterValue, pi.ParameterType, prop); })); } }
public void ChangeToCompatibleTypeLooksForTryParseMethod() { const string address = "127.0.0.1"; var value = TypeManipulation.ChangeToCompatibleType(address, typeof(IPAddress), null); Assert.That(value, Is.EqualTo(IPAddress.Parse(address))); }
public void ChangeToCompatibleType_UsesTypeConverterOnProperty() { var member = typeof(HasTypeConverterAttributes).GetProperty("Property"); var actual = TypeManipulation.ChangeToCompatibleType("25", typeof(Convertible), member) as Convertible; Assert.NotNull(actual); Assert.Equal(25, actual.Value); }
public void ChangeToCompatibleType_UsesTypeConverterOnParameter() { var ctor = typeof(HasTypeConverterAttributes).GetConstructor(new Type[] { typeof(Convertible) }); var member = ctor.GetParameters().First(); var actual = TypeManipulation.ChangeToCompatibleType("25", typeof(Convertible), member) as Convertible; Assert.NotNull(actual); Assert.Equal(25, actual.Value); }
/// <summary> /// Convert to the Autofac parameter type. /// </summary> /// <returns>The parameters represented by this collection.</returns> public IEnumerable <Parameter> ToParameters() { foreach (var parameter in this) { var localParameter = parameter; yield return(new ResolvedParameter( (pi, c) => pi.Name == localParameter.Name, (pi, c) => TypeManipulation.ChangeToCompatibleType(localParameter.CoerceValue(), pi.ParameterType, pi))); } }
public void ChangeToCompatibleType_UsesInvariantCulture(CultureInfo culture) { TestCulture.With( culture, () => { var actual = TypeManipulation.ChangeToCompatibleType("123.456", typeof(double)); Assert.Equal(123.456, actual); }); }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { Type instantiableType = ListElementCollection.ListElementTypeConverter.GetInstantiableType(destinationType); ListElementCollection listElementCollection = value as ListElementCollection; if (listElementCollection != null && instantiableType != null) { Type[] genericArguments = instantiableType.GetGenericArguments(); IList list = (IList)Activator.CreateInstance(instantiableType); foreach (ListItemElement current in listElementCollection) { list.Add(TypeManipulation.ChangeToCompatibleType(current.Value, genericArguments[0], null)); } return(list); } return(base.ConvertTo(context, culture, value, destinationType)); }
public IEnumerable <Parameter> ToParameters() { foreach (PropertyElement current in this) { PropertyElement localParameter = current; yield return(new ResolvedParameter(delegate(ParameterInfo pi, IComponentContext c) { PropertyInfo propertyInfo; return pi.TryGetDeclaringProperty(out propertyInfo) && propertyInfo.Name == localParameter.Name; }, delegate(ParameterInfo pi, IComponentContext c) { PropertyInfo memberInfo = null; pi.TryGetDeclaringProperty(out memberInfo); return TypeManipulation.ChangeToCompatibleType(localParameter.CoerceValue(), pi.ParameterType, memberInfo); })); } yield break; }
/// <summary> /// Reads configuration data for a component's metadata /// and updates the component registration as needed. /// </summary> /// <param name="component"> /// The configuration data containing the component. The <c>metadata</c> /// content will be read from this configuration object and used /// as the metadata values. /// </param> /// <param name="registrar"> /// The component registration to update with metadata. /// </param> /// <param name="defaultAssembly"> /// The default assembly, if any, from which unqualified type names /// should be resolved into types. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown if <paramref name="component" /> or <paramref name="registrar" /> is <see langword="null" />. /// </exception> protected virtual void RegisterComponentMetadata <TReflectionActivatorData, TSingleRegistrationStyle>(IConfiguration component, IRegistrationBuilder <object, TReflectionActivatorData, TSingleRegistrationStyle> registrar, Assembly defaultAssembly) where TReflectionActivatorData : ReflectionActivatorData where TSingleRegistrationStyle : SingleRegistrationStyle { if (component == null) { throw new ArgumentNullException(nameof(component)); } if (registrar == null) { throw new ArgumentNullException(nameof(registrar)); } foreach (var ep in component.GetSection("metadata").GetChildren()) { registrar.WithMetadata(ep["key"], TypeManipulation.ChangeToCompatibleType(ep["value"], ep.GetType("type", defaultAssembly))); } }
/// <summary> /// Convert to the Autofac parameter type. /// </summary> /// <returns>The parameters represented by this collection.</returns> public IEnumerable <Parameter> ToParameters() { foreach (var parameter in this) { var localParameter = parameter; yield return(new ResolvedParameter( (pi, c) => { PropertyInfo prop; return pi.TryGetDeclaringProperty(out prop) && prop.Name == localParameter.Name; }, (pi, c) => { PropertyInfo prop = null; pi.TryGetDeclaringProperty(out prop); return TypeManipulation.ChangeToCompatibleType(localParameter.CoerceValue(), pi.ParameterType, prop); })); } }
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { var instantiatableType = GetInstantiableType(destinationType); var castValue = value as ListElementCollection; if (castValue != null && instantiatableType != null) { Type[] generics = instantiatableType.GetGenericArguments(); var collection = (IList)Activator.CreateInstance(instantiatableType); foreach (var item in castValue) { collection.Add(TypeManipulation.ChangeToCompatibleType(item.Value, generics[0], null)); } return(collection); } return(base.ConvertTo(context, culture, value, destinationType)); }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { Type instantiableType = DictionaryElementCollection.DictionaryElementTypeConverter.GetInstantiableType(destinationType); DictionaryElementCollection dictionaryElementCollection = value as DictionaryElementCollection; if (dictionaryElementCollection != null && instantiableType != null) { IDictionary dictionary = (IDictionary)Activator.CreateInstance(instantiableType); Type[] genericArguments = instantiableType.GetGenericArguments(); foreach (ListItemElement current in dictionaryElementCollection) { if (string.IsNullOrEmpty(current.Key)) { throw new ConfigurationErrorsException("Key cannot be null in a dictionary element."); } object key = TypeManipulation.ChangeToCompatibleType(current.Key, genericArguments[0], null); object value2 = TypeManipulation.ChangeToCompatibleType(current.Value, genericArguments[1], null); dictionary.Add(key, value2); } return(dictionary); } return(base.ConvertTo(context, culture, value, destinationType)); }
public void ChangeToCompatibleType_NullReferenceType() { var actual = TypeManipulation.ChangeToCompatibleType(null, typeof(String)); Assert.Null(actual); }
public IEnumerable <Parameter> ToParameters() { foreach (ParameterElement current in this) { ParameterElement localParameter = current; yield return(new ResolvedParameter((ParameterInfo pi, IComponentContext c) => pi.Name == localParameter.Name, (ParameterInfo pi, IComponentContext c) => TypeManipulation.ChangeToCompatibleType(localParameter.CoerceValue(), pi.ParameterType, pi))); } yield break; }
public void ChangeToCompatibleType_NullValueType() { var actual = TypeManipulation.ChangeToCompatibleType(null, typeof(Int32)); Assert.Equal(0, actual); }
public void ChangeToCompatibleType_NoConversionNeeded() { var actual = TypeManipulation.ChangeToCompatibleType(15, typeof(Int32)); Assert.Equal(15, actual); }