ObserverUnitContainer.cs
2.97 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
75
76
77
78
79
80
using Microsoft.Extensions.Logging;
using Pole.Core.Observer;
using Pole.Core.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Pole.Core.EventBus.EventHandler;
using System.Linq;
using Pole.Core.Exceptions;
namespace Pole.Core.EventBus
{
public class ObserverUnitContainer : IObserverUnitContainer
{
readonly ConcurrentDictionary<string, List<object>> unitDict = new ConcurrentDictionary<string, List<object>>();
public ObserverUnitContainer(IServiceProvider serviceProvider)
{
var eventHandlerList = new List<(Type, EventHandlerAttribute)>();
foreach (var assembly in AssemblyHelper.GetAssemblies(serviceProvider.GetService<ILogger<ObserverUnitContainer>>()))
{
foreach (var type in assembly.GetTypes())
{
foreach (var attribute in type.GetCustomAttributes(false))
{
if (attribute is EventHandlerAttribute eventHandlerAttribute)
{
eventHandlerList.Add((type, eventHandlerAttribute));
break;
}
}
}
}
foreach (var eventHandler in eventHandlerList)
{
var unitType = typeof(ObserverUnit<>).MakeGenericType(new Type[] { typeof(string) });
var unit = (ObserverUnit<string>)Activator.CreateInstance(unitType, serviceProvider, eventHandler.Item1);
unit.Observer();
Register<string>(eventHandler.Item2.EventName, unit);
}
}
public List<IObserverUnit<PrimaryKey>> GetUnits<PrimaryKey>(string observerName)
{
if (unitDict.TryGetValue(observerName, out var units))
{
if (units is List<IObserverUnit<PrimaryKey>> result)
{
return result;
}
else
throw new UnmatchObserverUnitException(observerName);
}
else
throw new UnfindObserverUnitException(observerName);
}
public List<object> GetUnits(string observerName)
{
if (unitDict.TryGetValue(observerName, out var unit))
{
return unit;
}
else
throw new UnfindObserverUnitException(observerName);
}
public void Register<PrimaryKey>(string observerName, IGrainID observerUnit)
{
if (unitDict.TryGetValue(observerName, out List<object> units))
{
units.Add(observerUnit);
}
if (!unitDict.TryAdd(observerName, new List<object> { observerUnit }))
{
throw new ObserverUnitRepeatedException(observerUnit.EventHandlerType.FullName);
}
}
}
}