1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text.RegularExpressions;
- namespace Wayne.Lib.MessageBus
- {
- /// <summary>
- /// A very basic, fully synchronous bus implementation. The publish method
- /// will execute all subscribe actions.
- /// </summary>
- public class BasicBus : IBus
- {
- readonly object subscriptionsLock = new object();
- readonly List<SubscriptionBase> subscriptions = new List<SubscriptionBase>();
- public void Publish(string topic, object message)
- {
- SubscriptionBase[] iterationSubscriptions;
- lock (subscriptionsLock)
- {
- iterationSubscriptions = subscriptions.ToArray();
- }
- iterationSubscriptions
- .Where(x => x.TopicFilter.IsMatch(topic))
- .Where(x => x.Type.IsInstanceOfType(message))
- .ForEach(x =>
- {
- x.Invoke(topic, message);
- });
- }
- public IDisposable Subscribe<T>(string topicFilter, Action<string, T> action)
- {
- var subscription = new Subscription<T>()
- {
- TopicFilter = new Regex("^" + topicFilter.Replace("*", "[^/]*") + "$"),
- InvokeAction = action
- };
- lock (subscriptionsLock)
- {
- subscriptions.Add(subscription);
- }
- return new ActionDisposable(() =>
- {
- lock (subscriptionsLock)
- {
- subscriptions.Remove(subscription);
- }
- });
- }
- }
- }
|