CQRS+EventSourcing-创新互联

using System;
using System.Collections.Generic;
using System.Linq;

namespace CQRS
{
public class EventBroker
    {
public List AllEvents = new List();
public EventHandler Commands;
public EventHandler Queries;

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

public T Query(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(new AgeQuery(p));

            Console.WriteLine(res);

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

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

创新互联公司专注于石棉网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供石棉营销型网站建设,石棉网站制作、石棉网页设计、石棉网站官网定制、小程序制作服务,打造石棉网络公司原创品牌,更为您提供石棉网站排名全网营销落地服务。
网页名称:CQRS+EventSourcing-创新互联
文章路径:http://ybzwz.com/article/dchhgg.html