-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathAssemblyQualifiedNameMessageTypeResolver.cs
74 lines (57 loc) · 2.58 KB
/
AssemblyQualifiedNameMessageTypeResolver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
namespace SlimMessageBus.Host;
using System.Text.RegularExpressions;
using SlimMessageBus.Host.Collections;
/// <summary>
/// <see cref="IMessageTypeResolver"/> that uses the <see cref="Type.AssemblyQualifiedName"/> for mapping the <see cref="Type"/ to a string header value.
/// </summary>
public class AssemblyQualifiedNameMessageTypeResolver : IMessageTypeResolver
{
private static readonly Regex RedundantAssemblyTokens = new(@"\, (Version|Culture|PublicKeyToken)\=([\w\d.]+)", RegexOptions.None, TimeSpan.FromSeconds(2));
/// <summary>
/// Determines whether to emit the Version, Culture and PublicKeyToken along with the Assembly name (for strong assembly naming).
/// </summary>
public bool EmitAssemblyStrongName { get; set; } = false;
private readonly SafeDictionaryWrapper<Type, string> _toNameCache;
private readonly SafeDictionaryWrapper<string, Type> _toTypeCache;
private readonly IAssemblyQualifiedNameMessageTypeResolverRedirect[] _items;
public AssemblyQualifiedNameMessageTypeResolver(IEnumerable<IAssemblyQualifiedNameMessageTypeResolverRedirect> items = null)
{
_toNameCache = new SafeDictionaryWrapper<Type, string>(ToNameInternal);
_toTypeCache = new SafeDictionaryWrapper<string, Type>(ToTypeInternal);
_items = items is not null ? [.. items] : [];
}
private string ToNameInternal(Type messageType)
{
if (messageType is null) throw new ArgumentNullException(nameof(messageType));
string assemblyQualifiedName = null;
foreach (var item in _items)
{
assemblyQualifiedName = item.TryGetName(messageType);
if (assemblyQualifiedName is not null)
{
break;
}
}
assemblyQualifiedName ??= messageType.AssemblyQualifiedName;
if (!EmitAssemblyStrongName)
{
assemblyQualifiedName = RedundantAssemblyTokens.Replace(assemblyQualifiedName, string.Empty);
}
return assemblyQualifiedName;
}
private Type ToTypeInternal(string name)
{
if (name is null) throw new ArgumentNullException(nameof(name));
foreach (var item in _items)
{
var type = item.TryGetType(name);
if (type is not null)
{
return type;
}
}
return Type.GetType(name);
}
public string ToName(Type messageType) => _toNameCache.GetOrAdd(messageType);
public Type ToType(string name) => _toTypeCache.GetOrAdd(name);
}