コード例 #1
0
        async Task ProcessEventAsync(string eventName, string eventMessage)
        {
            if (!subscriptionsManager.HasSubscriptions(eventName))
            {
                return;
            }

            var eventType     = subscriptionsManager.GetEventType(eventName);
            var @event        = JsonSerializer.Deserialize(eventMessage, eventType);
            var handlerMethod = typeof(IEventHandler <>).MakeGenericType(eventType).GetMethod(nameof(IEventHandler <object> .HandleAsync));

            var handlerTypes = subscriptionsManager.GetEventHandlerTypes(eventName);

            using var scope = serviceProvider.CreateScope();
            foreach (var handlerType in handlerTypes)
            {
                try
                {
                    var handler = ActivatorUtilities.GetServiceOrCreateInstance(scope.ServiceProvider, handlerType);
                    await(Task) handlerMethod.Invoke(handler, new[] { @event });
                    logger.LogDebug($"{handlerType.FullName}=>{eventMessage}");
                }
                catch (Exception ex)
                {
                    logger.LogError($"{ex.Message} in {handlerType.FullName}=>{eventMessage}");
                }
            }
        }