Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
namespace DomainBindingTest
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var a = new Domain1();
a.Create();
Console.ReadKey();
}
}
public abstract class Event
{
}
public class CreatedEvent1 : Event
{
}
public abstract class Entity<TEntity> where TEntity : Entity<TEntity>
{
protected static Dictionary<Type, MethodInfo> EventHandlers;
static Entity()
{
EventHandlers = typeof (TEntity).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
.Where(x => x.Name.StartsWith("On"))
.ToDictionary(x => x.GetParameters().Single().ParameterType, x => x);
}
public virtual Guid Id { get; set; }
protected virtual void Fire(Event @event)
{
this.Apply(@event);
this.Publish(@event);
}
protected virtual void Publish(Event @event)
{
// Publish ...
}
public virtual void Apply(Event @event)
{
EventHandlers[@event.GetType()].Invoke(this, new[] {@event});
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
public override bool Equals(object obj)
{
var entity = obj as Entity<TEntity>;
if (entity == null)
{
return false;
}
return Id.Equals(entity.Id);
}
}
public class Domain1 : Entity<Domain1>
{
public void Create()
{
this.Fire(new CreatedEvent1());
}
protected void OnCreated(CreatedEvent1 @event)
{
Console.WriteLine("Created event called!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment