-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathEventTypeContainer.cs
More file actions
74 lines (67 loc) · 2.58 KB
/
EventTypeContainer.cs
File metadata and controls
74 lines (67 loc) · 2.58 KB
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
using System;
using System.Collections.Concurrent;
using System.Linq;
using Microsoft.Extensions.Logging;
using Vertex.Abstractions.Event;
using Vertex.Utils;
namespace Vertex.Runtime.Serialization
{
public class EventTypeContainer : IEventTypeContainer
{
private readonly ConcurrentDictionary<string, Type> nameDict = new();
private readonly ConcurrentDictionary<Type, string> typeDict = new();
private readonly ILogger<EventTypeContainer> logger;
public EventTypeContainer(ILogger<EventTypeContainer> logger, IEventNameGenerator eventNameGenerator)
{
this.logger = logger;
var baseEventType = typeof(IEvent);
var attributeType = typeof(EventNameAttribute);
foreach (var assembly in AssemblyHelper.GetAssemblies(this.logger))
{
foreach (var type in assembly.GetTypes())
{
if (baseEventType.IsAssignableFrom(type))
{
string eventName;
var attribute = type.GetCustomAttributes(attributeType, false).FirstOrDefault();
if (attribute != null && attribute is EventNameAttribute nameAttribute
&& nameAttribute.Name != default)
{
eventName = nameAttribute.Name;
}
else
{
eventName = eventNameGenerator.GetName(type);
}
if (!this.nameDict.TryAdd(eventName, type))
{
throw new OverflowException(eventName);
}
this.typeDict.TryAdd(type, eventName);
}
}
}
}
public bool TryGet(string name, out Type type)
{
var value = this.nameDict.GetOrAdd(name, key =>
{
foreach (var assembly in AssemblyHelper.GetAssemblies(this.logger))
{
var type = assembly.GetType(name, false);
if (type != default)
{
return type;
}
}
return Type.GetType(name, false);
});
type = value;
return value != default;
}
public bool TryGet(Type type, out string name)
{
return this.typeDict.TryGetValue(type, out name);
}
}
}