-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPublisher.cs
64 lines (53 loc) · 1.8 KB
/
Publisher.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 Autofac;
namespace ContinuousRunner
{
public class Publisher : IPublisher
{
public Publisher(ILifetimeScope scope)
{
_scope = scope;
}
private readonly ILifetimeScope _scope;
public void Publish<T>(T @event) where T : class
{
var exceptions = new List<Exception>();
foreach (dynamic handler in ResolveHandlers<T>())
{
try
{
handler.Handle((dynamic) @event);
}
catch (Exception exception)
{
exceptions.Add(exception);
}
}
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
}
public IEnumerable<dynamic> ResolveHandlers<T>() where T : class
{
return GetConcreteHandlers<T>().Union(GetInterfaceHandlers<T>());
}
private IEnumerable<dynamic> GetConcreteHandlers<T>() where T : class
{
return (IEnumerable<dynamic>) _scope.Resolve(MakeHandlerType(typeof(T)));
}
private IEnumerable<dynamic> GetInterfaceHandlers<T>() where T : class
{
var implementedInterfaces = typeof (T).GetTypeInfo().ImplementedInterfaces;
var resolved = implementedInterfaces.SelectMany(@interface => (IEnumerable<ISubscription<T>>) _scope.Resolve(MakeHandlerType(@interface)));
return resolved.Distinct();
}
private static Type MakeHandlerType(Type type)
{
return typeof (IEnumerable<>).MakeGenericType(typeof (ISubscription<>).MakeGenericType(type));
}
}
}