269
|
1 using System;
|
|
2 using System.Collections.Generic;
|
|
3 using System.Reflection;
|
|
4 using System.Xml;
|
|
5 using System.Xml.Serialization;
|
|
6 using Implab.Components;
|
|
7
|
|
8 namespace Implab.ServiceHost.Unity {
|
|
9 public class ConfigurationSchema {
|
|
10
|
|
11 public static ConfigurationSchema Default { get; private set; } = CreateDefault();
|
|
12
|
|
13 readonly Dictionary<Tuple<string,string>, LazyAndWeak<XmlSerializer>> m_mappings = new Dictionary<Tuple<string, string>, LazyAndWeak<XmlSerializer>>();
|
|
14
|
|
15 public void DefineMapping(string name, string ns, Type type) {
|
|
16 Safe.ArgumentNotEmpty(name, nameof(name));
|
|
17 Safe.ArgumentNotNull(type, nameof(type));
|
|
18 ns = ns ?? string.Empty;
|
|
19 m_mappings[Tuple.Create(name, ns)] = new LazyAndWeak<XmlSerializer>(() => new XmlSerializer(type), true);
|
|
20 }
|
|
21
|
|
22 public void DefineMapping<T>() {
|
|
23 var xmlRoot = typeof(T).GetCustomAttribute<XmlRootAttribute>();
|
|
24 var ns = xmlRoot?.Namespace;
|
|
25 var root = xmlRoot?.ElementName ?? typeof(T).Name;
|
|
26 DefineMapping(root, ns, typeof(T));
|
|
27 }
|
|
28
|
|
29 public T Deserialize<T>(XmlReader reader) {
|
|
30 reader.MoveToContent();
|
|
31 var name = reader.Name;
|
|
32 var ns = reader.NamespaceURI;
|
|
33
|
|
34 return (T)m_mappings[Tuple.Create(name, ns)].Value.Deserialize(reader);
|
|
35 }
|
|
36
|
|
37 static ConfigurationSchema CreateDefault() {
|
|
38 var schema = new ConfigurationSchema();
|
|
39
|
|
40 schema.DefineMapping<RegisterElement>();
|
271
|
41 schema.DefineMapping<IncludeElement>();
|
|
42 schema.DefineMapping<AssemblyElement>();
|
|
43 schema.DefineMapping<NamespaceElement>();
|
269
|
44
|
|
45 return schema;
|
|
46 }
|
|
47
|
|
48
|
|
49 }
|
|
50 } |