关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回

CQRS+EventSourcing

发布时间:2022-07-27 13:54:54
using System;
using System.Collections.Generic;
using System.Linq;

namespace CQRS
{
    public class EventBroker
    {
        public List<Event> AllEvents = new List<Event>();
        public EventHandler<Command> Commands;
        public EventHandler<Query> Queries;

        public void Command(Command cmd)
        {
            Commands.Invoke(this, cmd);
        }

        public T Query<T>(Query q)
        {
            Queries.Invoke(this, q);
            return (T)q.Result;
        }
    }

    public class Event
    {
    }

    public class Command : EventArgs
    {
    }

    public class Query
    {
        public object Result;
    }

    public class Person
    {
        private int age;
        EventBroker eventBroker;
        public Person(EventBroker eventBroker)
        {
            var self = this;
            this.eventBroker = eventBroker;
            this.eventBroker.Commands += (object sender, Command cmd) =>
            {
                var c = cmd as AgeChangedCommand;
                eventBroker.AllEvents.Add(new AgeChangedEvent(self, self.age, c.Age));
                self.age = c.Age;
            };
            this.eventBroker.Queries += (object sender, Query query) =>
            {
                var q = query as AgeQuery;
                q.Result = self.age;
            };
        }
    }

    public class AgeChangedEvent : Event
    {
        public Person Target;
        public int oldValue;
        public int newValue;

        public AgeChangedEvent(Person target, int oldVal, int newVal)
        {
            Target = target;
            oldValue = oldVal;
            newValue = newVal;
        }

        public override string ToString()
        {
            return $"Age changed from {oldValue} to {newValue}";
        }
    }

    public class AgeChangedCommand : Command
    {
        public Person Target;
        public int Age;

        public AgeChangedCommand(Person p, int age)
        {
            Target = p;
            Age = age;
        }
    }

    public class AgeQuery : Query
    {
        public Person Target;
        public AgeQuery(Person p)
        {
            Target = p;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            EventBroker eb = new EventBroker();
            Person p = new Person(eb);

            //command
            eb.Command(new AgeChangedCommand(p, 18));
            eb.Command(new AgeChangedCommand(p, 30));

            //event list
            foreach (var ev in eb.AllEvents)
            {
                Console.WriteLine(ev.ToString());
            }

            //query
            var res = eb.Query<int>(new AgeQuery(p));

            Console.WriteLine(res);

            Console.ReadKey();
        }
    }
}
下面是原视频:CQRS+EventSourci
ng

 https://www.bilibili.com/video/BV1HK411L7Lq/


/template/Home/DawnNew/PC/Static

立即注册风纳云账号,免费体验多款产品

立即注册