1: using System;
2: using System.ServiceModel;
3: using System.Collections.Generic;
4: using System.Collections.ObjectModel;
5: using System.Collections;
6:
7: namespace PublisherSubscriber2.Service
8: {
9: /// <summary>
10: /// PubSub service adapter.
11: /// </summary>
12: public class PubSubServiceAdapter : IPubSubService
13: {
14: #region Members
15:
16: private static List<IPubSubCallback> callbacks = new List<IPubSubCallback>();
17:
18: #endregion
19:
20: #region Public Methods
21:
22: /// <summary>
23: /// Operation used by the subscriber to subscribe to events published.
24: /// </summary>
25: public void Subscribe()
26: {
27: // Get callback contract
28:
29: IPubSubCallback callback = OperationContext.Current.GetCallbackChannel<IPubSubCallback>();
30:
31: // Add the subscriber callback to the list of active subscribers
32:
33: if (!callbacks.Contains(callback))
34: {
35: callbacks.Add(callback);
36: }
37: }
38:
39: /// <summary>
40: /// Operation used by the subscriber to unsubscribe to events published (stop receiving subscriptions).
41: /// </summary>
42: public void Unsubscribe()
43: {
44: // Get callback contract
45:
46: IPubSubCallback callback = OperationContext.Current.GetCallbackChannel<IPubSubCallback>();
47:
48: // Remove the subscriber callback from the list of active subscribers
49:
50: if (callbacks.Contains(callback))
51: {
52: callbacks.Remove(callback);
53: }
54: }
55:
56: /// <summary>
57: /// Operation used by the publisher to publish events.
58: /// </summary>
59: /// <param name="eventName">String that identifies the event published.</param>
60: public void PublishEvent(string eventName)
61: {
62: // Publish event to all active subscribers.
63:
64: CallSubscribers(eventName);
65: }
66:
67: #endregion
68:
69: #region Private Methods
70:
71: /// <summary>
72: /// Publishes the specified event to all active subscribers.
73: /// </summary>
74: /// <param name="eventName">Name of the event.</param>
75: private static void CallSubscribers(string eventName)
76: {
77: // Build callback action
78:
79: Action<IPubSubCallback> invoke = delegate(IPubSubCallback callback)
80: {
81: callback.EventPublished(eventName);
82: };
83:
84: // Call callback for every registered subscriber.
85:
86: callbacks.ForEach(invoke);
87: }
88:
89: #endregion
90: }
91: }