2

In the separation of concerns, I have a Controller, Handler, and Repository. If I want the database IO to be done asynchronously, where should I put the async method?

For instance, I currently have the following:

In the Controller

public async Task<ActionResult> CreateOrder(OrderCreateModel ocm)
{
    var order = await Using<CreateOffer>().Exeucte(ocm, userID);
    ...
}

In the Handler

public async Task<Order> Execute(OrderCreateModel ocm, Guid userID)
{
    ...
    return await _ordersRepository.CreateOrderAsync(new Order(ConvertToDataObject(ocm, userID));
}

And finally, in the Repository

public async Task<Order> CreateOrderAsync(Order newOrder)
{
    context.orders.Add(newOrder);
    await context.SaveChangesAsync();
    return newOrder;
}

It seems like this is too many Async methods. Would I get the same results if I:

  1. just make the repository method async (and all the above methods synchronous)?
  2. Or if I just make the Controller method Async (and make all the underlying calls synchronous)?

What would be the best practices traversing the different layers to make the data operation asynchronous?

1 Answer 1

2

You currently have the right approach. It's a know issue called "async all the way down". Basically it means that if you need some code to be async, all the calling methods should be async too. You shouldn't mix sync and async code, as it's easy to deadlock and/or to entirely defeat the purpose of asynchronous code (i.e. scalability).

So in your case, the code you wrote follow the best practices.

See this amazing article (really, it's the best article about the subject IMHO) for other best practices. Note the "Async All the Way" chapter is essentially the answer to the question you have.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! And the article is great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.