/
EventTypeMapper.cs
40 lines (28 loc) · 1.2 KB
/
EventTypeMapper.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
namespace Core.Events;
public class EventTypeMapper
{
public static readonly EventTypeMapper Instance = new();
private readonly ConcurrentDictionary<string, Type?> typeMap = new();
private readonly ConcurrentDictionary<Type, string> typeNameMap = new();
public void AddCustomMap<T>(string eventTypeName) => AddCustomMap(typeof(T), eventTypeName);
public void AddCustomMap(Type eventType, string eventTypeName)
{
typeNameMap.AddOrUpdate(eventType, eventTypeName, (_, typeName) => typeName);
typeMap.AddOrUpdate(eventTypeName, eventType, (_, type) => type);
}
public string ToName<TEventType>() => ToName(typeof(TEventType));
public string ToName(Type eventType) => typeNameMap.GetOrAdd(eventType, _ =>
{
var eventTypeName = eventType.FullName!;
typeMap.TryAdd(eventTypeName, eventType);
return eventTypeName;
});
public Type? ToType(string eventTypeName) => typeMap.GetOrAdd(eventTypeName, _ =>
{
var type = TypeProvider.GetFirstMatchingTypeFromCurrentDomainAssembly(eventTypeName);
if (type == null)
return null;
typeNameMap.TryAdd(type, eventTypeName);
return type;
});
}