aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Core/DI/TangoMessenger.cs
blob: 0064faae048a33ed9aae190e29a6dbfa3efd416c (plain)
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tango.Core.DI
{
    /// <summary>
    /// Represents the Tango messenger service.
    /// </summary>
    public class TangoMessenger
    {
        private class MessageHandler
        {
            public Type Type { get; set; }
            public Action<object> Handler { get; set; }

            public MessageHandler(Type type, Action<object> handler)
            {
                Type = type;
                Handler = handler;
            }
        }

        private List<MessageHandler> _messageHandlers;

        private static TangoMessenger _default;
        /// <summary>
        /// Gets the default messenger instance.
        /// </summary>
        public static TangoMessenger Default
        {
            get
            {
                if (_default == null)
                {
                    _default = new TangoMessenger();
                }

                return _default;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TangoMessenger"/> class.
        /// </summary>
        public TangoMessenger()
        {
            _messageHandlers = new List<MessageHandler>();
        }

        /// <summary>
        /// Registers the specified message handler.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="handler">The handler.</param>
        public void Register<T>(Action<T> handler)
        {
            _messageHandlers.Add(new MessageHandler(typeof(T), (x) => handler((T)x)));
        }

        /// <summary>
        /// Sends the specified message.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message">The message.</param>
        public void Send<T>(T message)
        {
            foreach (var handler in _messageHandlers.Where(x => x.Type == typeof(T)))
            {
                handler.Handler(message);
            }
        }
    }
}