Skip to content

@sickboy /Context
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
readonly ICollection<Action> _transactionCallbacks = new Collection<Action>();
public override int SaveChanges() {
int r;
try {
ExecuteDomainEvents();
r = base.SaveChanges();
} catch (Exception) {
_transactionCallbacks.Clear();
throw;
}
ExecuteTransactionCallbacks();
return r;
}
public override async Task<int> SaveChangesAsync() {
int r;
try {
ExecuteDomainEvents();
r = await base.SaveChangesAsync().ConfigureAwait(false);
} catch (Exception) {
_transactionCallbacks.Clear();
throw;
}
ExecuteTransactionCallbacks();
return r;
}
public override async Task<int> SaveChangesAsync(CancellationToken cts) {
int r;
try {
ExecuteDomainEvents();
r = await base.SaveChangesAsync(cts).ConfigureAwait(false);
} catch (Exception) {
_transactionCallbacks.Clear();
throw;
}
ExecuteTransactionCallbacks();
return r;
}
void ExecuteDomainEvents() {
foreach (var entity in GetEntitiesWithPendingEvents())
ExecuteEntityEvents(entity);
}
IEntity[] GetEntitiesWithPendingEvents() {
return ChangeTracker.Entries<IEntity>()
.Select(po => po.Entity)
.Where(po => po.Events.Any())
.ToArray();
}
void ExecuteEntityEvents(IEntity entity) {
var events = entity.Events.ToArray();
entity.Events.Clear();
foreach (var domainEvent in events)
_mediator.Notify(domainEvent);
}
public void AddTransactionCallback(Action act) {
_transactionCallbacks.Add(act);
}
void ExecuteTransactionCallbacks() {
var callbacks = _transactionCallbacks.ToArray();
_transactionCallbacks.Clear();
foreach (var c in callbacks)
c();
}
public void AddChatMessage(string message, Account account) {
Contract.Requires<ArgumentNullException>(message != null);
Contract.Requires<ArgumentNullException>(account != null);
var chatHubMessage = new ChatHubMessage(message, account);
ChatMessages.Add(chatHubMessage);
Events.Add(new ChatHubMessageCreated(this, chatHubMessage));
}
public class SendChatMessageToSignalR : SignalRBaseHandler<IChatMessenger>,
INotificationHandler<ChatHubMessageCreated>
{
public SendChatMessageToSignalR(ISqlContext context, IChatMessenger messenger) : base(context, messenger) {}
public void Handle(ChatHubMessageCreated notification) {
Context.AddTransactionCallback(
() =>
Messenger.SendChatMessage(notification.ChatHub.Uuid,
notification.ChatHubMessage.Map<ChatMessageModel>()));
}
}
public class ChatHubMessageCreated : IDomainEvent
{
public ChatHubMessageCreated(ChatHub chatHub, ChatHubMessage chatHubMessage) {
Contract.Requires<ArgumentNullException>(chatHub != null);
Contract.Requires<ArgumentNullException>(chatHubMessage != null);
ChatHub = chatHub;
ChatHubMessage = chatHubMessage;
}
public ChatHub ChatHub { get; private set; }
public ChatHubMessage ChatHubMessage { get; private set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.