예제 #1
0
    private void PublishAndForget(IEnumerable <MediatorListenerDescription> listeners, object notification, string key, PublishOptions options)
    {
        Task.Run(async() =>
        {
            var context = new ServiceLikeContext(key, options.Header);

            try
            {
                var listenersList = listeners.ToList();
                _logger.TraceStartPublishToListeners(key, listenersList);

                using var scope = _scopedServiceFactoryFactory.Create();

                var contextAccessors = scope.Instance.GetInstances <IServiceLikeContextAccessor>();
                if (contextAccessors.Any())
                {
                    contextAccessors.First().Context = context;
                }

                var publishTasks        = new List <Task>();
                var serviceLikeMediator = new ServiceLikeMediator(scope.Instance);

                if (options.BeforePublishAsyncHandler is not null)
                {
                    await options.BeforePublishAsyncHandler.Invoke(notification, context).ConfigureAwait(false);
                }

                foreach (var listener in listenersList)
                {
                    try
                    {
                        var value = TranslateType(notification, listener.ListenerType);
                        _logger.TracePublishToListener(listener);
                        publishTasks.Add(FireEvent(listener, serviceLikeMediator, value !));
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorOnPublish(ex, listener);
                    }
                }
                // すべて投げたまでで完了とする。
                if (options.CompleteAsyncHandler is not null)
                {
                    await options.CompleteAsyncHandler.Invoke(notification, context).ConfigureAwait(false);
                }
                _logger.TraceFinishPublishToListeners(key);

                await Task.WhenAll(publishTasks);
            }
            catch (Exception e)
            {
                if (options.ErrorAsyncHandler is not null)
                {
                    await options.ErrorAsyncHandler.Invoke(e, notification, context).ConfigureAwait(false);
                }
                _logger.ErrorOnPublishEvents(e, key);
            }
        }).ConfigureAwait(false);
    }
예제 #2
0
 private Task FireEvent(MediatorListenerDescription description, ServiceLikeMediator serviceLikeMediator,
                        object eventData)
 => description.MediateType == MediateType.Notification
         ? serviceLikeMediator.Publish(eventData)
         : serviceLikeMediator.Send(eventData);