ActivityFinder.cs
2.1 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
using Microsoft.Extensions.Logging;
using Pole.Core.Utils;
using Pole.Sagas.Client.Abstraction;
using Pole.Sagas.Core.Abstraction;
using Pole.Sagas.Core.Exceptions;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pole.Sagas.Client
{
public class ActivityFinder : IActivityFinder
{
private readonly ConcurrentDictionary<string, Type> nameDict = new ConcurrentDictionary<string, Type>();
private readonly ConcurrentDictionary<Type, string> typeDict = new ConcurrentDictionary<Type, string>();
readonly ILogger<ActivityFinder> logger;
public ActivityFinder(ILogger<ActivityFinder> logger)
{
this.logger = logger;
var baseActivityType = typeof(IActivity<>);
foreach (var assembly in AssemblyHelper.GetAssemblies(this.logger))
{
foreach (var type in assembly.GetTypes().Where(m => m.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == baseActivityType) && m.IsClass && !m.IsAbstract))
{
if (!type.FullName.EndsWith("Activity"))
{
throw new ActivityNameIrregularException(type);
}
var activityName = type.Name.Substring(0, type.Name.Length - "Activity".Length);
typeDict.TryAdd(type, activityName);
if (!nameDict.TryAdd(activityName, type))
{
throw new ActivityNameRepeatedException(activityName);
}
}
}
}
public Type FindType(string name)
{
if (nameDict.TryGetValue(name, out Type type))
{
return type;
}
throw new ActivityNotFoundByNameException(name);
}
public string GetName(Type type)
{
if (!typeDict.TryGetValue(type, out var value))
throw new ActivityNotFoundByTypeException(type);
return value;
}
}
}