In my current application in payment gateway, I want to perform this steps
- Transfer fund from paypal .
- Save the payment record in database
- Increase the user’s fund(which is in our database) by the amount he transferred.
I am performing all this steps in app layer. Inside transaction scope
Below is the code
public void DepositFundInAdvertiser(PaymentInfo paymentInfo, RegistrationID advertiserRegistrationID)
{
using (TransactionScope scope = new TransactionScope())
{
PaymentResult paymentResult = paymentService.DepositFund(paymentInfo);
Advertiser advertiser = advertiserRepository.Find(advertiserRegistrationID);
TransactionNumber transactionNumber = paymentRepository.NextTransactionNumber();
Payment payment = PaymentFactory.NewPayment(advertiser.Person, transactionNumber, paymentInfo, paymentResult);
paymentRepository.Save(payment);
AdvertiserBalance newBalance = new AdvertiserBalance(advertiser.Balance.Amount + paymentInfo.PaymentTotal);//Increasing advertiser fund
advertiser.AddFund(newBalance);
advertiserRepository.Save(advertiser);
scope.Complete();
}
}
Problem : My question is can i use Transactionscope in app layer like this, because all this operation should be atomic ?
I would say it’s a good compromise between complexity and robustness. You only have to keep in mind that by doing this you couple both repositories. You won’t be able to change either one without considering the effect of this change to the other one and to transaction infrastructure. As long as both repositories use the same database instance or RDBMS that fully supports distributed transactions, everything is fine. Sort of.
As you probably know, the pure solution is async messaging, but it introduces a lot of complexity. The thing is, the complexity connected with async messaging tends to be flat — it doesn’t grow as you add more repositories, more data stores etc. It pays off in the long run. If you have one such use case, I would go with the solution you proposed. As I said, it’s good compromise and making software is about good compromises.