Skip to content

Instantly share code, notes, and snippets.

@dcomartin dcomartin/handler.cs

Last active Mar 26, 2016
Embed
What would you like to do?
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
You can’t perform that action at this time.