feanz
2/12/2015 - 9:17 AM

Example event model

Example event model


    public interface IEventPublisher
    {
        void Publish<T>(T item) where T : IEvent;
    }

    public interface IHandler<in T> where T : IEvent
    {
        void Handle(T item);
    }

    public interface IEvent
    {
        DateTime DatePublished { get; set; }
    }

    public class EventPublisher : IEventPublisher
    {
        private readonly ILifeTimeScope _lifeTimeScope;

        public EventPublisher(ILifeTimeScope lifeTimeScope)
        {
            _lifeTimeScope = lifeTimeScope;
        }

        public void Publish<T>(T item) where T : IEvent
        {
            //add error handling and logging 
            var handlers = _lifeTimeScope.Resolve<IEnumerable<IHandler<T>>>();

            foreach (var handler in handlers)
            {
                handler.Handle(item);
            }
        }
    }

    public interface IProfileUpdateEventHandler
    {
        void Handle(SiteProfile oldProfileValue, SiteProfile newProfileValue);
    }

    public class ProfileUpdateEventDispatcher
    {
        private readonly IEnumerable<IProfileUpdateEventHandler> _profileUpdateEventHandlers;

        public ProfileUpdateEventDispatcher(IEnumerable<IProfileUpdateEventHandler> profileUpdateEventHandlers)
        {
            _profileUpdateEventHandlers = profileUpdateEventHandlers;
        }

        public void Handle(SiteProfile oldProfileValue, SiteProfile newProfileValue)
        {
            foreach (var handler in _profileUpdateEventHandlers)
            {
                handler.Handle(oldProfileValue, newProfileValue);
            }
        }
    }

    public class KycChangedProfileUpdateHandler :IProfileUpdateEventHandler
    {
        private readonly IEventPublisher _eventPublisher;

        public KycChangedProfileUpdateHandler(IEventPublisher eventPublisher)
        {
            _eventPublisher = eventPublisher;
        }

        public void Handle(SiteProfile oldProfileValue, SiteProfile newProfileValue)
        {
            if (oldProfileValue.PlayerStatuses.AccountStatus != newProfileValue.PlayerStatuses.AccountStatus)
            {
                _eventPublisher.Publish(new KycChangedEvent());
            }
        }
    }

    public class KycChangedEvent : IEvent
    {
        //other properties here

        public DateTime DatePublished { get; set; }
    }