268
|
1 using System;
|
|
2 using System.Collections.Generic;
|
|
3 using System.Text.RegularExpressions;
|
|
4 using Implab.Diagnostics;
|
|
5
|
|
6 namespace Implab.ServiceHost.Unity {
|
|
7 using System.Linq;
|
|
8 using System.Text;
|
|
9 using static Trace<ConfigurationContext>;
|
|
10
|
|
11 public class ConfigurationContext {
|
|
12 Regex _nsRx = new Regex(@"^\w+(\.\w+)*$", RegexOptions.Compiled);
|
|
13 readonly LinkedList<string> m_namespases = new LinkedList<string>();
|
|
14
|
|
15 LinkedListNode<string> m_insertAt;
|
|
16
|
|
17 public ConfigurationContext() {
|
|
18 m_insertAt = new LinkedListNode<string>(string.Empty);
|
|
19 m_namespases.AddFirst(m_insertAt);
|
|
20 }
|
|
21
|
|
22 public void AddNamespace(string ns) {
|
|
23 Safe.ArgumentMatch(ns, nameof(ns), _nsRx);
|
|
24 if (m_insertAt != null)
|
|
25 m_namespases.AddAfter(m_insertAt, ns);
|
|
26 else
|
|
27 m_namespases.AddFirst(ns);
|
|
28 }
|
|
29
|
|
30 public Type Resolve(TypeReference reference) {
|
|
31 Safe.ArgumentNotNull(reference, nameof(reference));
|
|
32
|
|
33 var args = reference.IsGeneric && !reference.IsOpenGeneric ? reference.GenericParameters?.Select(Resolve).ToArray() : null;
|
|
34 var argc = reference.IsGeneric ? reference.GenericParameters.Length : 0;
|
|
35
|
|
36 foreach (var ns in m_namespases) {
|
|
37 var typeName = FormatName(new [] { ns, reference.Namespace, reference.TypeName}, argc, args, reference.IsArray);
|
|
38
|
|
39 var resolved = Type.GetType(typeName, false);
|
|
40 if (resolved != null) {
|
|
41 Log("Probe succeed {0} in '{1}': {2} -> {3}", reference, ns, typeName, resolved.FullName);
|
|
42 return resolved;
|
|
43 } else {
|
|
44 Log("Probe failed {0} in '{1}': {2}", reference, ns, typeName);
|
|
45 }
|
|
46 }
|
|
47
|
|
48 throw new Exception($"Failed to resolve: {reference}");
|
|
49 }
|
|
50
|
|
51 string FormatName(string[] parts, int argc, Type[] args, bool isArray) {
|
|
52 var builder = new StringBuilder();
|
|
53
|
|
54 builder.Append(String.Join(".", parts.Where(x => !string.IsNullOrEmpty(x))));
|
|
55 if (argc > 0) {
|
|
56 builder.Append('`');
|
|
57 builder.Append(argc);
|
|
58 }
|
|
59
|
|
60 if (args!= null && args.Length > 0) {
|
|
61 builder.Append('[');
|
|
62 builder.Append(string.Join(",", args.Select(x => x.FullName)));
|
|
63 builder.Append(']');
|
|
64 }
|
|
65
|
|
66 if(isArray)
|
|
67 builder.Append("[]");
|
|
68
|
|
69 return builder.ToString();
|
|
70 }
|
|
71
|
|
72 public Type Resolve(string typeReference) {
|
|
73 return Resolve(TypeReference.Parse(typeReference));
|
|
74 }
|
|
75
|
|
76 public void Register(ServiceElement descriptor) {
|
|
77
|
|
78 }
|
|
79
|
|
80 }
|
|
81 } |