using System; using System.ComponentModel; using System.Xml.Serialization; using Unity.Injection; namespace Implab.ServiceHost.Unity { public class InjectionValueBuilder { readonly TypeResolver m_resolver; public Type DefaultType { get; private set; } public Type ValueType { get; set; } public object Value { get; set; } public InjectionParameterValue Injection { get { if (Value != null) return InjectionParameterValue.ToParameter(Value); return new InjectionParameter(ValueType, null); } } internal InjectionValueBuilder(TypeResolver resolver, Type acceptsType) { m_resolver = resolver; DefaultType = acceptsType; } public Type ResolveType(string typeSpec) { if (string.IsNullOrEmpty(typeSpec)) { if (DefaultType == null) throw new Exception("The type must be specified"); return DefaultType; } return m_resolver.Resolve(typeSpec); } public void Visit(ITextValue value) { ValueType = ResolveType(value.TypeName); Value = string.IsNullOrEmpty(value.Value) ? Safe.CreateDefaultValue(ValueType) : TypeDescriptor.GetConverter(ValueType).ConvertFromString(value.Value); } public void Visit(ISerializedValue value) { ValueType = ResolveType(value.TypeName); var serializer = new XmlSerializer(ValueType); using (var reader = value.GetReader()) Value = new InjectionParameter(ValueType, serializer.Deserialize(reader)); } public void Visit(IDependencyReference value) { ValueType = ResolveType(value.TypeName); Value = new ResolvedParameter(ValueType, value.DependencyName); } } }