These days it is common for the data layer to interact asynchronously with the DB:
public async Task<Customer> GetCustomer(int id)
{
using (db = new AppDbContext())
{
return await db.Customers.FindAsync(id);
}
}
With this technique, it is my understanding that all calling methods, all the way to the UI layer, then must also be defined with the async keyword. Thus you end up with an application where every method or function that eventually interacts with the DB be an async method.
This seems terribly messy and "pollutes" all the application layers with knowledge of an implementation detail inside the data layer.
Am I misunderstanding something or is this simply what one has to do?
async
contextual keyword everywhere, but it does make sense for it to be synchronous all the way down or asynchronous all the way down. The only exemption to this I can think of would be where you compose multiple asynchronous operations to query multiple sources, then synchronously return a composite data structure."Am I misunderstanding something"
- Yes. The code should be "async all the way down". The idea is that the top-level application layer can manage operations which have asynchronous components in deeper layers that it doesn't need to know about. The components themselves still return the same information and still encapsulate how they arrive at that information. The only difference is when they return it, which is an architectural consideration and not an implementation detail.