|
|
using System;
|
|
|
using System.Collections.Generic;
|
|
|
using System.Reflection;
|
|
|
using System.Xml;
|
|
|
using System.Xml.Serialization;
|
|
|
using Implab.Components;
|
|
|
|
|
|
namespace Implab.ServiceHost.Unity {
|
|
|
public class ConfigurationSchema {
|
|
|
|
|
|
public static ConfigurationSchema Default { get; private set; } = CreateDefault();
|
|
|
|
|
|
readonly Dictionary<Tuple<string,string>, LazyAndWeak<XmlSerializer>> m_mappings = new Dictionary<Tuple<string, string>, LazyAndWeak<XmlSerializer>>();
|
|
|
|
|
|
public void DefineMapping(string name, string ns, Type type) {
|
|
|
Safe.ArgumentNotEmpty(name, nameof(name));
|
|
|
Safe.ArgumentNotNull(type, nameof(type));
|
|
|
ns = ns ?? string.Empty;
|
|
|
m_mappings[Tuple.Create(name, ns)] = new LazyAndWeak<XmlSerializer>(() => new XmlSerializer(type), true);
|
|
|
}
|
|
|
|
|
|
public void DefineMapping<T>() {
|
|
|
var xmlRoot = typeof(T).GetCustomAttribute<XmlRootAttribute>();
|
|
|
var ns = xmlRoot?.Namespace;
|
|
|
var root = xmlRoot?.ElementName ?? typeof(T).Name;
|
|
|
DefineMapping(root, ns, typeof(T));
|
|
|
}
|
|
|
|
|
|
public T Deserialize<T>(XmlReader reader) {
|
|
|
reader.MoveToContent();
|
|
|
var name = reader.Name;
|
|
|
var ns = reader.NamespaceURI;
|
|
|
|
|
|
return (T)m_mappings[Tuple.Create(name, ns)].Value.Deserialize(reader);
|
|
|
}
|
|
|
|
|
|
static ConfigurationSchema CreateDefault() {
|
|
|
var schema = new ConfigurationSchema();
|
|
|
|
|
|
schema.DefineMapping<RegisterElement>();
|
|
|
|
|
|
return schema;
|
|
|
}
|
|
|
|
|
|
|
|
|
}
|
|
|
}
|