/// <summary> /// Asynchronously registers a handler. /// </summary> /// <param name="handlerFactory">The handler to register.</param> /// <returns>A task representing the asynchronous operation.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="handlerFactory"/> is null.</exception> public async Task RegisterAsync(IContextualProvider <THandler> handlerFactory) { if (handlerFactory == null) { throw new ArgumentNullException(nameof(handlerFactory)); } Debug.Assert(_handlerStack != null); Debug.Assert(_lock != null); using (await _lock.LockAsync()) { if (_handlerStack.IsEmpty) { await PushHandler(handlerFactory); await _dispatchForwarding.RegisterForwardingAsync(); } else { var tos = _handlerStack.Last(); Debug.Assert(tos != null); if (handlerFactory.Equals(tos)) { await _dispatchForwarding.RegisterForwardingAsync(); return; } if (tos is IDeactivationNotifyable notifyable) { await notifyable.NotifyDeactivationAsync(); } _handlerStack = _handlerStack.Remove(handlerFactory); await PushHandler(handlerFactory); await _dispatchForwarding.RegisterForwardingAsync(); } } }
/// <summary> /// Asynchronously registers a handler. /// </summary> /// <param name="handlerFactory">The handler to register.</param> /// <returns>A task representing the asynchronous operation.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="handlerFactory"/> is null.</exception> public async Task RegisterAsync(IContextualProvider <THandler> handlerFactory) { if (handlerFactory == null) { throw new ArgumentNullException(nameof(handlerFactory)); } Debug.Assert(_handlers != null); Debug.Assert(_lock != null); using (await _lock.LockAsync()) { var handlers = _handlers.Add(handlerFactory); if (handlers == _handlers) { return; } if (_handlers.IsEmpty) { await _dispatchForwarding.RegisterForwardingAsync(); } if (_handlers.Count == 1 && _handlers.First() is IDeactivationNotifyable deactivationNotifyable) { await deactivationNotifyable.NotifyDeactivationAsync(); } _handlers = handlers; if (handlers.Count == 1 && handlerFactory is IActivationNotifyable activationNotifyable) { await activationNotifyable.NotifyActivationAsync(); } } }