diff Implab.ServiceHost/Unity/InjectionValueBuilder.cs @ 274:22629bf26121 v3

Unity xml configuration, alpha2
author cin
date Fri, 27 Apr 2018 04:47:52 +0300
parents
children 963b17c275be
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Implab.ServiceHost/Unity/InjectionValueBuilder.cs	Fri Apr 27 04:47:52 2018 +0300
@@ -0,0 +1,64 @@
+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);
+        }
+
+    }
+}
\ No newline at end of file