Skip to content

Instantly share code, notes, and snippets.

@jrgcubano
Created August 20, 2017 17:38
Show Gist options
  • Save jrgcubano/5e527b042c40b628f35b7430eeb57269 to your computer and use it in GitHub Desktop.
Save jrgcubano/5e527b042c40b628f35b7430eeb57269 to your computer and use it in GitHub Desktop.
CQRS Example parts (ValueObject, ...)
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace EventFlow.ValueObjects
{
public abstract class ValueObject
{
private static readonly ConcurrentDictionary<Type, IReadOnlyCollection<PropertyInfo>> TypeProperties = new ConcurrentDictionary<Type, IReadOnlyCollection<PropertyInfo>>();
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
if (ReferenceEquals(null, obj)) return false;
if (GetType() != obj.GetType()) return false;
var other = obj as ValueObject;
return other != null && GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());
}
public override int GetHashCode()
{
unchecked
{
return GetEqualityComponents().Aggregate(17, (current, obj) => current * 23 + (obj?.GetHashCode() ?? 0));
}
}
public static bool operator ==(ValueObject left, ValueObject right)
{
return Equals(left, right);
}
public static bool operator !=(ValueObject left, ValueObject right)
{
return !Equals(left, right);
}
public override string ToString()
{
return $"{{{string.Join(", ", GetProperties().Select(f => $"{f.Name}: {f.GetValue(this)}"))}}}";
}
protected virtual IEnumerable<object> GetEqualityComponents()
{
return GetProperties().Select(x => x.GetValue(this));
}
protected virtual IEnumerable<PropertyInfo> GetProperties()
{
return TypeProperties.GetOrAdd(
GetType(),
t => t
.GetTypeInfo()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.OrderBy(p => p.Name)
.ToList());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment