-
Notifications
You must be signed in to change notification settings - Fork 3
/
Dispatcher.cs
56 lines (49 loc) · 1.82 KB
/
Dispatcher.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
using System.Collections.Generic;
namespace ClassLibrary4
{
public class Dispatcher : IPublishEvents
{
private readonly IDictionary<string, Multiplexor<Message>> router = new Dictionary<string,Multiplexor<Message>>();
public void Subscribe<T>(Handles<T> handler) where T : Message
{
Subscribe(typeof(T).Name, handler);
}
public void Subscribe<T>(string topic, Handles<T> handler) where T : Message
{
Multiplexor<Message> multiplexor;
if (false == router.TryGetValue(topic, out multiplexor))
{
multiplexor = new Multiplexor<Message>();
router.Add(topic, multiplexor);
}
multiplexor.Add(new NarrowingHandler<T, Message>(handler));
}
public void Unsubscribe<T>(Handles<T> handler) where T : Message
{
Unsubscribe(typeof(T).Name, handler);
}
public void Unsubscribe<T>(string topic, Handles<T> handler) where T : Message
{
Multiplexor<Message> multiplexor;
if (false == router.TryGetValue(topic, out multiplexor))
return;
multiplexor.Remove(new NarrowingHandler<T, Message>(handler));
}
public void Publish(string topic, Message message)
{
Multiplexor<Message> handler;
if (router.TryGetValue(topic, out handler))
{
handler.Handle(message);
}
if (router.TryGetValue(message.CorrelationId.ToString(), out handler))
{
handler.Handle(message);
}
}
public void Publish<T>(T message) where T : Message
{
Publish(typeof(T).Name, message);
}
}
}