Skip to content

Commit

Permalink
Updated the domain event implementation.
Browse files Browse the repository at this point in the history
  • Loading branch information
daxnet committed Dec 18, 2012
1 parent 8b5b2d8 commit 648cedd
Show file tree
Hide file tree
Showing 12 changed files with 75 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,5 @@ C:\Users\chenqiny\Documents\GitHub\ByteartRetail\ByteartRetail.DataObjects\obj\D
C:\Users\chenqiny\Documents\GitHub\ByteartRetail\ByteartRetail.DataObjects\obj\Debug\ByteartRetail.DataObjects.csprojResolveAssemblyReference.cache
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.DataObjects\bin\Debug\ByteartRetail.DataObjects.dll
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.DataObjects\bin\Debug\ByteartRetail.DataObjects.pdb
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.DataObjects\obj\Debug\ByteartRetail.DataObjects.csprojResolveAssemblyReference.cache
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.DataObjects\obj\Debug\ByteartRetail.DataObjects.dll
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.DataObjects\obj\Debug\ByteartRetail.DataObjects.pdb
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,21 @@ public EntityFrameworkRepositoryContext(IBus bus) : base(bus) { }

public override void RegisterDeleted<TAggregateRoot>(TAggregateRoot obj)
{
this.AddPendingEvent(obj, obj.UncommittedEvents);
localCtx.Value.Set<TAggregateRoot>().Remove(obj);
Committed = false;
}

public override void RegisterModified<TAggregateRoot>(TAggregateRoot obj)
{
this.AddPendingEvent(obj, obj.UncommittedEvents);
localCtx.Value.Entry<TAggregateRoot>(obj).State = System.Data.EntityState.Modified;
Committed = false;
}

public override void RegisterNew<TAggregateRoot>(TAggregateRoot obj)
{
this.AddPendingEvent(obj, obj.UncommittedEvents);
localCtx.Value.Set<TAggregateRoot>().Add(obj);
Committed = false;
}
Expand Down
43 changes: 18 additions & 25 deletions ByteartRetail.Domain/Repositories/RepositoryContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using ByteartRetail.Events.Bus;
using System.Transactions;
using ByteartRetail.Domain.Events;
using ByteartRetail.Events;

namespace ByteartRetail.Domain.Repositories
{
Expand All @@ -20,6 +21,7 @@ public abstract class RepositoryContext : DisposableObject, IRepositoryContext
private readonly ThreadLocal<Dictionary<Guid, object>> localModifiedCollection = new ThreadLocal<Dictionary<Guid, object>>(() => new Dictionary<Guid, object>());
private readonly ThreadLocal<Dictionary<Guid, object>> localDeletedCollection = new ThreadLocal<Dictionary<Guid, object>>(() => new Dictionary<Guid, object>());
private readonly ThreadLocal<bool> localCommitted = new ThreadLocal<bool>(() => true);
private readonly ThreadLocal<Dictionary<IAggregateRoot, List<IEvent>>> pendingEvents = new ThreadLocal<Dictionary<IAggregateRoot, List<IEvent>>>(() => new Dictionary<IAggregateRoot, List<IEvent>>());
private readonly IBus bus;
#endregion

Expand All @@ -37,9 +39,6 @@ public RepositoryContext(IBus bus)
/// <remarks>Note that this can only be called after the repository context has successfully committed.</remarks>
protected void ClearRegistrations()
{
//this.newCollection.Clear();
//this.modifiedCollection.Clear();
//this.localDeletedCollection.Value.Clear();
this.localNewCollection.Value.Clear();
this.localModifiedCollection.Value.Clear();
this.localDeletedCollection.Value.Clear();
Expand All @@ -56,6 +55,13 @@ protected override void Dispose(bool disposing)
}
}

protected void AddPendingEvent(IAggregateRoot aggregateRoot, IEnumerable<IEvent> evnts)
{
if (this.pendingEvents.Value.ContainsKey(aggregateRoot))
this.pendingEvents.Value[aggregateRoot].AddRange(evnts);
else
this.pendingEvents.Value.Add(aggregateRoot, new List<IEvent>(evnts));
}
protected abstract void DoCommit();
#endregion

Expand Down Expand Up @@ -174,26 +180,11 @@ public virtual void Commit()
Action funcCommit = () =>
{
this.DoCommit();
List<IDomainEvent> domainEvents = new List<IDomainEvent>();
foreach (var item in localNewCollection.Value)
{
var aggregateRoot = (item.Value as IAggregateRoot);
domainEvents.AddRange(aggregateRoot.UncommittedEvents);
}
foreach (var item in localModifiedCollection.Value)
{
var aggregateRoot = (item.Value as IAggregateRoot);
domainEvents.AddRange(aggregateRoot.UncommittedEvents);
}
foreach (var item in localDeletedCollection.Value)
{
var aggregateRoot = (item.Value as IAggregateRoot);
domainEvents.AddRange(aggregateRoot.UncommittedEvents);
}
domainEvents
.OrderBy(de => de.TimeStamp)
this.pendingEvents
.Value
.Values
.ToList()
.ForEach(p => bus.Publish(p));
.ForEach(p => p.ForEach(q => bus.Publish(q)));
};
if (this.bus.IsDistributedTransactionSupported)
{
Expand All @@ -204,9 +195,11 @@ public virtual void Commit()
}
else
funcCommit();
localNewCollection.Value.ToList().ForEach(kvp => (kvp.Value as IAggregateRoot).ClearEvents());
localModifiedCollection.Value.ToList().ForEach(kvp => (kvp.Value as IAggregateRoot).ClearEvents());
localDeletedCollection.Value.ToList().ForEach(kvp => (kvp.Value as IAggregateRoot).ClearEvents());
this.pendingEvents
.Value
.Keys
.ToList()
.ForEach(p => p.ClearEvents());
}
/// <summary>
/// Rolls-back the UnitOfWork.
Expand Down
10 changes: 8 additions & 2 deletions ByteartRetail.Events/Bus/EventDispatcher.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using ByteartRetail.Events.Handlers;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

Expand Down Expand Up @@ -36,7 +37,7 @@ public EventDispatcher(EventDispatchMode dispatchMode, IEventHandler<TEvent>[] e
}
#endregion

#region IEventAggregator<TEvent> Members
#region IEventDispatcher<TEvent> Members
/// <summary>
/// 向Event Aggreator注册用于处理<c>TEvent</c>类型的事件处理器。
/// </summary>
Expand Down Expand Up @@ -68,7 +69,12 @@ public virtual void DispatchEvent(TEvent domainEvent)
}
#endregion

#region IEventAggregator Members
#region IEventDispatcher Members

public Type EventType
{
get { return typeof(TEvent); }
}
/// <summary>
/// 向Event Aggreator注册用于处理<c>IDomainEvent</c>类型的事件处理器。
/// </summary>
Expand Down
29 changes: 15 additions & 14 deletions ByteartRetail.Events/Bus/EventDispatcherBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,32 @@ namespace ByteartRetail.Events.Bus
public class EventDispatcherBus : IBus
{
#region Private Fields
private static Dictionary<Type, IEventDispatcher> eventDispatchers = new Dictionary<Type, IEventDispatcher>();
//private static Dictionary<Type, IEventDispatcher> eventDispatchers = new Dictionary<Type, IEventDispatcher>();
private readonly List<IEventDispatcher> eventDispatchers = new List<IEventDispatcher>();
#endregion

public EventDispatcherBus()
public EventDispatcherBus(IEventDispatcher[] eventDispatchers)
{

this.eventDispatchers.AddRange(eventDispatchers);
}

public static void RegisterDispatchersFor<TEvent>()
where TEvent : class, IEvent
{
if (eventDispatchers.ContainsKey(typeof(TEvent)))
return;
IEventDispatcher<TEvent> eventDispatcher = ServiceLocator
.Instance
.GetService<IEventDispatcher<TEvent>>(); // 从IoC容器中解析应用于给定事件类型的事件聚合器实例。
//public static void RegisterDispatchersFor<TEvent>()
// where TEvent : class, IEvent
//{
// if (eventDispatchers.ContainsKey(typeof(TEvent)))
// return;
// IEventDispatcher<TEvent> eventDispatcher = ServiceLocator
// .Instance
// .GetService<IEventDispatcher<TEvent>>(); // 从IoC容器中解析应用于给定事件类型的事件聚合器实例。

eventDispatchers.Add(typeof(TEvent), eventDispatcher); // 将事件聚合器实例添加到线程的本地存储中。
}
// eventDispatchers.Add(typeof(TEvent), eventDispatcher); // 将事件聚合器实例添加到线程的本地存储中。
//}

#region IBus Members

public void Publish<TEvent>(TEvent evnt) where TEvent : class, IEvent
{
var eventDispatcher = eventDispatchers[typeof(TEvent)];
var eventDispatcher = this.eventDispatchers.Where(p => p.EventType == evnt.GetType()).FirstOrDefault();
if (eventDispatcher != null)
eventDispatcher.DispatchEvent(evnt);
}
Expand Down
3 changes: 3 additions & 0 deletions ByteartRetail.Events/Bus/IEventDispatcher.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

using ByteartRetail.Events.Handlers;
using System;

namespace ByteartRetail.Events.Bus
{
Expand All @@ -15,6 +16,8 @@ public interface IEventDispatcher
/// 获取领域事件的派发方式。
/// </summary>
EventDispatchMode DispatchMode { get; }

Type EventType { get; }
#endregion

#region Methods
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,5 @@ C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Infrastructure\
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Infrastructure\bin\Debug\Microsoft.Practices.Unity.Configuration.xml
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Infrastructure\bin\Debug\Microsoft.Practices.Unity.Interception.xml
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Infrastructure\bin\Debug\Microsoft.Practices.Unity.Interception.Configuration.xml
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Infrastructure\obj\Debug\ByteartRetail.Infrastructure.csprojResolveAssemblyReference.cache
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Infrastructure\obj\Debug\ByteartRetail.Infrastructure.dll
C:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Infrastructure\obj\Debug\ByteartRetail.Infrastructure.pdb
Binary file modified ByteartRetail.Services/App_Data/ByteartRetail.mdf
Binary file not shown.
Binary file modified ByteartRetail.Services/App_Data/ByteartRetail_log.ldf
Binary file not shown.
3 changes: 2 additions & 1 deletion ByteartRetail.Services/Global.asax.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using ByteartRetail.Domain.Model;
using ByteartRetail.Domain.Repositories.EntityFramework;
using ByteartRetail.Events.Bus;
using ByteartRetail.Infrastructure;
using System;

namespace ByteartRetail.Services
Expand All @@ -14,13 +15,13 @@ protected void Application_Start(object sender, EventArgs e)
{
ByteartRetailDbContextInitailizer.Initialize();
ApplicationService.Initialize();
EventDispatcherBus.RegisterDispatchersFor<OrderDispatchedEvent>();
DomainEventAggregator.Subscribe<OrderDispatchedEvent>(p =>
{
SalesOrder salesOrder = p.Source as SalesOrder;
salesOrder.DateDispatched = p.DispatchedDate;
salesOrder.Status = SalesOrderStatus.Dispatched;
});
IBus bus = ServiceLocator.Instance.GetService<IBus>();
log4net.Config.XmlConfigurator.Configure();
}

Expand Down
13 changes: 13 additions & 0 deletions ByteartRetail.Services/Logs/balog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -572,3 +572,16 @@ Parameter name: obj
at ByteartRetail.Domain.Repositories.Repository`1.Add(TAggregateRoot aggregateRoot) in c:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Domain\Repositories\Repository.cs:line 355
at ByteartRetail.Application.Implementation.OrderServiceImpl.AddProductToCart(Guid customerID, Guid productID, Int32 quantity) in c:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Application\Implementation\OrderServiceImpl.cs:line 82
at DynamicModule.ns.Wrapped_IOrderService_36e4cd1cd41f46acac6483c4fc61452b.<AddProductToCart_DelegateImplementation>__1(IMethodInvocation inputs, GetNextInterceptionBehaviorDelegate getNext)

2012-12-18 22:26:32,399 [11] ERROR ByteartRetail.Logger - Exception caught
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at ByteartRetail.Events.Bus.EventDispatcherBus.Publish[TEvent](TEvent evnt) in c:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Events\Bus\EventDispatcherBus.cs:line 38
at ByteartRetail.Domain.Repositories.RepositoryContext.<Commit>b__c(IEvent q) in c:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Domain\Repositories\RepositoryContext.cs:line 187
at System.Collections.Generic.List`1.ForEach(Action`1 action)
at ByteartRetail.Domain.Repositories.RepositoryContext.<Commit>b__b(List`1 p) in c:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Domain\Repositories\RepositoryContext.cs:line 187
at System.Collections.Generic.List`1.ForEach(Action`1 action)
at ByteartRetail.Domain.Repositories.RepositoryContext.<Commit>b__a() in c:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Domain\Repositories\RepositoryContext.cs:line 183
at ByteartRetail.Domain.Repositories.RepositoryContext.Commit() in c:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Domain\Repositories\RepositoryContext.cs:line 197
at ByteartRetail.Application.Implementation.OrderServiceImpl.Dispatch(Guid orderID) in c:\Users\Sunny Chen\Documents\GitHub\ByteartRetail\ByteartRetail.Application\Implementation\OrderServiceImpl.cs:line 172
at DynamicModule.ns.Wrapped_IOrderService_7de737716a634c3e8a94fca000261808.<Dispatch_DelegateImplementation>__7(IMethodInvocation inputs, GetNextInterceptionBehaviorDelegate getNext)
17 changes: 13 additions & 4 deletions ByteartRetail.Services/Web.config
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,10 @@
<register type="ByteartRetail.Events.Handlers.IEventHandler`1[[ByteartRetail.Domain.Events.OrderDispatchedEvent, ByteartRetail.Domain]], ByteartRetail.Events"
mapTo="ByteartRetail.Events.Handlers.OrderDispatchedSendEmailHandler, ByteartRetail.Events.Handlers"
name="OrderDispatchedSendEmailHandler"/>
<!--Event Aggreators-->
<register type="ByteartRetail.Events.Bus.IEventDispatcher`1[[ByteartRetail.Domain.Events.OrderDispatchedEvent, ByteartRetail.Domain]], ByteartRetail.Events"
mapTo="ByteartRetail.Events.Bus.EventDispatcher`1[[ByteartRetail.Domain.Events.OrderDispatchedEvent, ByteartRetail.Domain]], ByteartRetail.Events">
<!--Event Dispatchers-->
<register type="ByteartRetail.Events.Bus.IEventDispatcher, ByteartRetail.Events"
mapTo="ByteartRetail.Events.Bus.EventDispatcher`1[[ByteartRetail.Domain.Events.OrderDispatchedEvent, ByteartRetail.Domain]], ByteartRetail.Events"
name="OrderDispatchedEventDispatcher">
<constructor>
<param name="dispatchMode">
<value value="Sequential" />
Expand All @@ -79,7 +80,15 @@
</register>
<!--Event Bus-->
<register type="ByteartRetail.Events.Bus.IBus, ByteartRetail.Events"
mapTo="ByteartRetail.Events.Bus.EventDispatcherBus, ByteartRetail.Events" />
mapTo="ByteartRetail.Events.Bus.EventDispatcherBus, ByteartRetail.Events">
<constructor>
<param name="eventDispatchers">
<array>
<dependency name="OrderDispatchedEventDispatcher"/>
</array>
</param>
</constructor>
</register>
</container>
</unity>
<!--END: Unity-->
Expand Down

0 comments on commit 648cedd

Please sign in to comment.