1
1
using System ;
2
2
using System . Collections . Generic ;
3
+ using System . Linq ;
4
+ using System . Reflection ;
3
5
using JetBrains . Annotations ;
4
6
5
7
namespace Eventuous {
6
8
[ PublicAPI ]
7
9
public static class TypeMap {
10
+ static readonly List < Assembly > Assemblies = new ( ) ;
11
+
8
12
static readonly Dictionary < string , Type > ReverseMap = new ( ) ;
9
13
static readonly Dictionary < Type , string > Map = new ( ) ;
10
14
11
15
public static string GetTypeName < T > ( ) => Map [ typeof ( T ) ] ;
12
-
16
+
13
17
public static string GetTypeName ( object o ) => Map [ o . GetType ( ) ] ;
14
-
18
+
15
19
public static string GetTypeNameByType ( Type type ) => Map [ type ] ;
16
20
17
21
public static Type GetType ( string typeName ) => ReverseMap [ typeName ] ;
18
-
19
- public static bool TryGetType ( string typeName , out Type ? type ) => ReverseMap . TryGetValue ( typeName , out type ) ;
20
22
21
- public static void AddType < T > ( string name ) {
22
- ReverseMap [ name ] = typeof ( T ) ;
23
- Map [ typeof ( T ) ] = name ;
23
+ public static bool TryGetType ( string typeName , out Type ? type ) {
24
+ return ReverseMap . TryGetValue ( typeName , out type ) ;
25
+ }
26
+
27
+ public static void AddType < T > ( string name ) => AddType ( typeof ( T ) , name ) ;
28
+
29
+ static void AddType ( Type type , string name ) {
30
+ ReverseMap [ name ] = type ;
31
+ Map [ type ] = name ;
24
32
}
25
33
26
34
public static bool IsTypeRegistered < T > ( ) => Map . ContainsKey ( typeof ( T ) ) ;
35
+
36
+ public static void RegisterKnownEventTypes ( params Assembly [ ] assemblies ) {
37
+ foreach ( var assembly in assemblies ) {
38
+ RegisterAssemblyEventTypes ( assembly ) ;
39
+ }
40
+ }
41
+
42
+ static Type _attributeType = typeof ( EventTypeAttribute ) ;
43
+
44
+ static void RegisterAssemblyEventTypes ( Assembly assembly ) {
45
+ var decoratedTypes = assembly . DefinedTypes . Where (
46
+ x => x . IsClass && x . CustomAttributes . Any ( a => a . AttributeType == _attributeType )
47
+ ) ;
48
+
49
+ foreach ( var type in decoratedTypes ) {
50
+ var attr = ( EventTypeAttribute ) Attribute . GetCustomAttribute ( type , _attributeType ) ! ;
51
+ AddType ( type , attr . EventType ) ;
52
+ }
53
+ }
54
+ }
55
+
56
+ [ AttributeUsage ( AttributeTargets . Class ) ]
57
+ public class EventTypeAttribute : Attribute {
58
+ public string EventType { get ; }
59
+
60
+ public EventTypeAttribute ( string eventType ) => EventType = eventType ;
27
61
}
28
- }
62
+ }
0 commit comments