Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Last active March 26, 2016 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/33628230fb49d7293ced to your computer and use it in GitHub Desktop.
Save dcomartin/33628230fb49d7293ced to your computer and use it in GitHub Desktop.
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