Last active
March 26, 2016 15:12
-
-
Save dcomartin/33628230fb49d7293ced 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
public class ChangeCustomerPricingLevel : IAsyncRequest | |
{ | |
public Guid CustomerId { get; } | |
public PricingLevel PricingLevel { get; } | |
public ChangeCustomerPricingLevel(Guid customerId, PricingLevel pricingLevel) | |
{ | |
CustomerId = customerId; | |
PricingLevel = pricingLevel; | |
} | |
} | |
public class CustomerPricingLevelChanged : IAsyncNotification | |
{ | |
public Guid CustomerId { get; } | |
public PricingLevel PricingLevel { get; } | |
public CustomerPricingLevelChanged(Guid customerId, PricingLevel pricingLevel) | |
{ | |
CustomerId = customerId; | |
PricingLevel = pricingLevel; | |
} | |
} | |
public class ChangeCustomerPricingLevelHandler : IAsyncRequestHandler<Envelope<ChangeCustomerPricingLevel>, Unit> | |
{ | |
private readonly IMediator _mediator; | |
private readonly CustomerContext _db; | |
public ChangeCustomerPricingLevelHandler(IMediator mediator, CustomerContext db) | |
{ | |
_mediator = mediator; | |
_db = db; | |
} | |
public async Task<Unit> Handle(Envelope<ChangeCustomerPricingLevel> message) | |
{ | |
using (var transaction = _db.Database.BeginTransaction()) | |
{ | |
_db.IdempotentIds.Add(new Idempotent { IdempotentId = message.MessageId }); | |
try | |
{ | |
await _db.SaveChangesAsync(); | |
} | |
catch (MySqlException ex) | |
{ | |
// Duplicate Key Error Number | |
if (ex.Number == 1062) return Unit.Value; | |
throw; | |
} | |
var customer = _db.Customers.SingleOrDefault(x => x.CustomerId == message.Body.CustomerId); | |
if (customer == null) throw new InvalidOperationException(); | |
customer.PrivingLevel = message.Body.PricingLevel; | |
await _db.SaveChangesAsync(); | |
transaction.Commit(); | |
} | |
var evnt = new CustomerPricingLevelChanged(customer.CustomerId, message.Body.PricingLevel); | |
var envelop = new Envelope<CustomerPricingLevelChanged>(message.CorrelationId, evnt); | |
await _mediator.PublishAsync(envelop); | |
return Unit.Value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment