/// <summary> /// Initializes a new instance of the <see cref="SubscriptionEventInfo"/> class. /// </summary> /// <param name="parent">Parent container.</param> /// <param name="eventName">Name of the event sending notification.</param> public SubscriptionEventInfo(SubscriptionContainerInfo parent, string eventName) { Subscribers = new List <SubscriberInfo>(); EventName = eventName; _parent = parent; }
/// <summary> /// Creates a new subscription. If a subscription with the same parameters already exists, nothing happens. /// </summary> /// <typeparam name="TSubscribeTo">Type of object being subscribed to, that will transmit event.</typeparam> /// <typeparam name="TSubscriber">Type of object receiving notifications.</typeparam> /// <param name="subscribeToEvent">Name of the event to subscribe to.</param> /// <param name="subscriber">Object receiving notifications.</param> /// <param name="eventHandler">Method that will be invoked to handle notification.</param> public static void Subscribe <TSubscribeTo, TSubscriber>(string subscribeToEvent, TSubscriber subscriber, EventHandler eventHandler) { SubscriptionContainerInfo newSubscriptionContainer = null; SubscriptionEventInfo newEventInfo = null; SubscriberInfo newSubscriber = null; var subscribeToContainerType = typeof(TSubscribeTo); var subscriberType = typeof(TSubscriber); var currentSubscriptions = _subscriptions.Where(x => x.SubscribeToContainerType == subscribeToContainerType); foreach (var subscriptionContainer in currentSubscriptions) { var eventInfos = subscriptionContainer.Events.Where(x => x.EventName == subscribeToEvent); foreach (var eventInfo in eventInfos) { var existingSubscriber = eventInfo .Subscribers .Where(x => x.SubscriberType == subscriberType && x.Handler == eventHandler) .FirstOrDefault(); if (!object.ReferenceEquals(null, existingSubscriber)) { return; } newSubscriber = new SubscriberInfo(eventInfo, subscriber, subscriberType, eventHandler); eventInfo.Subscribers.Add(newSubscriber); return; } // else, not found in Events. newEventInfo = new SubscriptionEventInfo(subscriptionContainer, subscribeToEvent); newSubscriber = new SubscriberInfo(newEventInfo, subscriber, subscriberType, eventHandler); newEventInfo.Subscribers.Add(newSubscriber); subscriptionContainer.Events.Add(newEventInfo); return; } // else, not found in current subscriptions newSubscriptionContainer = new SubscriptionContainerInfo(subscribeToContainerType); newEventInfo = new SubscriptionEventInfo(newSubscriptionContainer, subscribeToEvent); newSubscriber = new SubscriberInfo(newEventInfo, subscriber, subscriberType, eventHandler); newEventInfo.Subscribers.Add(newSubscriber); newSubscriptionContainer.Events.Add(newEventInfo); _subscriptions.Add(newSubscriptionContainer); }
private static void RemoveSubscriptionContainer(SubscriptionContainerInfo item) { _subscriptions.Remove(item); item = null; }