Created
January 19, 2014 17:41
-
-
Save mat3u/8508287 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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