##// END OF EJS Templates
Implemented typereference parser
Implemented typereference parser

File last commit:

r268:0be8a6ae8307 v3
r268:0be8a6ae8307 v3
Show More
ConfigurationContext.cs
80 lines | 2.7 KiB | text/x-csharp | CSharpLexer
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Implab.Diagnostics;
namespace Implab.ServiceHost.Unity {
using System.Linq;
using System.Text;
using static Trace<ConfigurationContext>;
public class ConfigurationContext {
Regex _nsRx = new Regex(@"^\w+(\.\w+)*$", RegexOptions.Compiled);
readonly LinkedList<string> m_namespases = new LinkedList<string>();
LinkedListNode<string> m_insertAt;
public ConfigurationContext() {
m_insertAt = new LinkedListNode<string>(string.Empty);
m_namespases.AddFirst(m_insertAt);
}
public void AddNamespace(string ns) {
Safe.ArgumentMatch(ns, nameof(ns), _nsRx);
if (m_insertAt != null)
m_namespases.AddAfter(m_insertAt, ns);
else
m_namespases.AddFirst(ns);
}
public Type Resolve(TypeReference reference) {
Safe.ArgumentNotNull(reference, nameof(reference));
var args = reference.IsGeneric && !reference.IsOpenGeneric ? reference.GenericParameters?.Select(Resolve).ToArray() : null;
var argc = reference.IsGeneric ? reference.GenericParameters.Length : 0;
foreach (var ns in m_namespases) {
var typeName = FormatName(new [] { ns, reference.Namespace, reference.TypeName}, argc, args, reference.IsArray);
var resolved = Type.GetType(typeName, false);
if (resolved != null) {
Log("Probe succeed {0} in '{1}': {2} -> {3}", reference, ns, typeName, resolved.FullName);
return resolved;
} else {
Log("Probe failed {0} in '{1}': {2}", reference, ns, typeName);
}
}
throw new Exception($"Failed to resolve: {reference}");
}
string FormatName(string[] parts, int argc, Type[] args, bool isArray) {
var builder = new StringBuilder();
builder.Append(String.Join(".", parts.Where(x => !string.IsNullOrEmpty(x))));
if (argc > 0) {
builder.Append('`');
builder.Append(argc);
}
if (args!= null && args.Length > 0) {
builder.Append('[');
builder.Append(string.Join(",", args.Select(x => x.FullName)));
builder.Append(']');
}
if(isArray)
builder.Append("[]");
return builder.ToString();
}
public Type Resolve(string typeReference) {
return Resolve(TypeReference.Parse(typeReference));
}
public void Register(ServiceElement descriptor) {
}
}
}