comparison Implab.ServiceHost/Unity/ContainerConfigurationSchema.cs @ 273:79110a16cab7 v3

Working on Unity xml configuration: Refactoring in progress
author cin
date Thu, 26 Apr 2018 19:35:01 +0300
parents
children 22629bf26121
comparison
equal deleted inserted replaced
272:9d1cca834b05 273:79110a16cab7
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Reflection;
5 using System.Xml;
6 using System.Xml.Serialization;
7 using Implab.Components;
8
9 namespace Implab.ServiceHost.Unity {
10 public class ContainerConfigurationSchema {
11
12 public static ContainerConfigurationSchema Default { get; private set; } = CreateDefault();
13
14 readonly LazyAndWeak<XmlSerializer> m_seralizer;
15
16 readonly XmlAttributeOverrides m_overrides = new XmlAttributeOverrides();
17
18 readonly XmlAttributes m_containerItems = new XmlAttributes();
19
20 public XmlSerializer Serializer {
21 get {
22 return m_seralizer.Value;
23 }
24 }
25
26 public ContainerConfigurationSchema() {
27 m_overrides.Add(typeof(ContainerElement), nameof(ContainerElement.Items), m_containerItems);
28
29 m_seralizer = new LazyAndWeak<XmlSerializer>(() => new XmlSerializer(typeof(ContainerElement), m_overrides));
30 }
31
32 public void RegisterContainerElement(Type type, string name) {
33 Safe.ArgumentNotNull(type, nameof(type));
34 Safe.ArgumentNotEmpty(name, nameof(name));
35
36 if(!type.IsSubclassOf(typeof(ContainerItemElement)))
37 throw new Exception($"RegisterContainerElement '{name}': {type} must be subclass of {typeof(ContainerItemElement)}");
38
39 m_containerItems.XmlElements.Add(
40 new XmlElementAttribute(name, type)
41 );
42 }
43
44 public void RegisterContainerElement<T>(string name) where T : ContainerItemElement {
45 RegisterContainerElement(typeof(T), name);
46 }
47
48 public ContainerElement LoadFile(string file) {
49 using (var reader = XmlReader.Create(file)) {
50 return (ContainerElement)Serializer.Deserialize(reader);
51 }
52 }
53
54 static ContainerConfigurationSchema CreateDefault() {
55 var schema = new ContainerConfigurationSchema();
56
57 schema.RegisterContainerElement<RegisterElement>("register");
58 schema.RegisterContainerElement<IncludeElement>("include");
59 schema.RegisterContainerElement<AssemblyElement>("assembly");
60 schema.RegisterContainerElement<NamespaceElement>("namespace");
61
62 return schema;
63 }
64
65
66 }
67 }