generated from CodelyTV/csharp-basic-skeleton
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathDomainEventSubscriberServices.cs
64 lines (54 loc) · 2.32 KB
/
DomainEventSubscriberServices.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using CodelyTv.Shared.Domain.Bus.Event;
using CodelyTv.Shared.Infrastructure.Bus.Event;
using Microsoft.Extensions.DependencyInjection;
namespace CodelyTv.Shared
{
public static class DomainEventSubscriberInformationService
{
public static IServiceCollection AddDomainEventSubscriberInformationService(this IServiceCollection services,
Assembly assembly)
{
var information =
new Dictionary<Type, DomainEventSubscriberInformation>();
var classTypes = assembly.ExportedTypes.Select(t => t.GetTypeInfo()).Where(t => t.IsClass && !t.IsAbstract);
foreach (var type in classTypes)
{
var interfaces = type.ImplementedInterfaces.Select(i => i.GetTypeInfo());
foreach (var handlerInterfaceType in interfaces.Where(i =>
i.IsGenericType && i.GetGenericTypeDefinition() == typeof(DomainEventSubscriber<>)))
{
services.AddScoped(handlerInterfaceType.AsType(), type.AsType());
FormatSubscribers(assembly, handlerInterfaceType, information);
}
}
services.AddScoped(s => new DomainEventSubscribersInformation(information));
return services;
}
private static void FormatSubscribers(Assembly assembly, TypeInfo handlerInterfaceType,
Dictionary<Type, DomainEventSubscriberInformation> information)
{
var handlerClassTypes = assembly.GetLoadableTypes()
.Where(handlerInterfaceType.IsAssignableFrom);
var eventType = handlerInterfaceType.GenericTypeArguments.FirstOrDefault();
if (eventType == null) return;
foreach (var handlerClassType in handlerClassTypes)
information.Add(handlerClassType,
new DomainEventSubscriberInformation(handlerClassType, eventType));
}
private static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null);
}
}
}
}