DDD领域驱动设计:领域基础设施层2016-03-21 cnblogs 刘标才其实这里说的基础设施层只是领域层的一些接口和基类而已,没有其他的如日子工具等代码,仅仅是为了说明领域层的一些基础问题1、领域事件简单实现代码,都是来至ASP.NET设计模式书中的代码
namespace DDD.Infrastructure.Domain.Events{public interface IDomainEvent{}}
namespace DDD.Infrastructure.Domain.Events{public interface IDomainEventHandler<T> : IDomainEventHandlerwhere T : IDomainEvent{void Handle(T e);} public interface IDomainEventHandler{ } }
namespace DDD.Infrastructure.Domain.Events{public interface IDomainEventHandlerFactory{IEnumerable<IDomainEventHandler<T>> GetDomainEventHandlersFor<T>(T domainEvent)where T : IDomainEvent;} }
namespace DDD.Infrastructure.Domain.Events{public class StructureMapDomainEventHandlerFactory : IDomainEventHandlerFactory{public IEnumerable<IDomainEventHandler<T>> GetDomainEventHandlersFor<T>(T domainEvent) where T : IDomainEvent{return ObjectFactory.GetAllInstances<IDomainEventHandler<T>>();}} }
namespace DDD.Infrastructure.Domain.Events{public static class DomainEvents{public static IDomainEventHandlerFactory DomainEventHandlerFactory { get; set; } public static void Raise<T>(T domainEvent) where T : IDomainEvent{var handlers = DomainEventHandlerFactory.GetDomainEventHandlersFor(domainEvent);foreach (var item in handlers){item.Handle(domainEvent);}}}}
2、领域层接口代码,很多都是来至MS NLayer代码和google code
namespace DDD.Infrastructure.Domain{public interface IEntity<out TId>{TId Id { get; }}}
namespace DDD.Infrastructure.Domain{public interface IAggregateRoot : IAggregateRoot<string>{} public interface IAggregateRoot<out TId> : IEntity<TId>{}}
namespace DDD.Infrastructure.Domain{public abstract class EntityBase : EntityBase<string>{protected EntityBase():this(null){} protected EntityBase(string id){this.Id = id;} public override string Id{get{return base.Id;}set{base.Id = value;if (string.IsNullOrEmpty(this.Id)){this.Id = EntityBase.NewId();}}} public static string NewId(){return Guid.NewGuid().ToString("N");}} public abstract class EntityBase<TId> : IEntity<TId>{public virtual TId Id{get;set;} public virtual IEnumerable<BusinessRule> Validate(){return new BusinessRule[] { };} public override bool Equals(object entity){return entity != null && entity is EntityBase<TId> && this == (EntityBase<TId>)entity;} public override int GetHashCode(){return this.Id.GetHashCode();} public static bool operator ==(EntityBase<TId> entity1, EntityBase<TId> entity2){if ((object)entity1 == null && (object)entity2 == null){return true;} if ((object)entity1 == null || (object)entity2 == null){return false;} if (entity1.Id.ToString() == entity2.Id.ToString()){return true;} return false;} public static bool operator !=(EntityBase<TId> entity1, EntityBase<TId> entity2){return (!(entity1 == entity2));}} }