Ejemplo n.º 1
0
        public ResourceEventPublisher(Storage <T> storage, EventClient messageClient, ILogger <ResourceEventPublisher <T> > logger)
        {
            EventHandler <T> publish(ResourceEventType type) => (sender, eventArgs) => messageClient.Publish(type, eventArgs);

            var eventsToEmit = typeof(T).GetAttributeValue((EmitEventsAttribute attr) => attr.EventTypes);


            if (eventsToEmit.Contains(ResourceEventType.Created))
            {
                storage.OnCreate += publish(ResourceEventType.Created);
            }

            if (eventsToEmit.Contains(ResourceEventType.Updated))
            {
                storage.OnUpdate += publish(ResourceEventType.Updated);
            }

            if (eventsToEmit.Contains(ResourceEventType.Deleted))
            {
                storage.OnDelete += publish(ResourceEventType.Deleted);
            }

            logger.LogDebug("Event publisher for resource {ResourceType} initialized. Emitting {EventTypes} events", typeof(T).Name, eventsToEmit);
        }
Ejemplo n.º 2
0
        public ResourceEventListener(ILogger <ResourceEventListener <T> > logger, EventClient messageClient)
        {
            // If type T is defined in the same service that's running
            if (typeof(T).Assembly.GetName().Name.StartsWith(BlockInfo.Name))
            {
                logger.LogCritical("The resource {ResourceType} is defined in the same service as it's event listener. Please use the other constructor and supply a {StorageName} object", typeof(T), nameof(Storage <T>));
                throw new ArgumentException($"Provide a {nameof(Storage<T>)} not a {nameof(EventClient)} for types defined in the same service");
            }

            messageClient.MessageReceived += (sender, args) =>
            {
                if (args.Resource?.GetType() == typeof(T))
                {
                    logger.LogInformation("{EventType} event received for {Resource}", args.EventType, (T)args.Resource);
                    switch (args.EventType)
                    {
                    case ResourceEventType.Created when CreateIsOverride:
                        OnCreate(args.Resource);
                        break;

                    case ResourceEventType.Updated when UpdateIsOverride:
                        OnUpdate(args.Resource);
                        break;

                    case ResourceEventType.Deleted when DeleteIsOverride:
                        OnDelete(args.Resource);
                        break;
                    }
                    ;
                }
            };



            logger.LogDebug("External listener {ListenerName} initialized. Listening to {EventTypes} events", GetType().Name, ListeningTo());
        }