M
M
Michael2019-01-28 01:43:21
ASP.NET
Michael, 2019-01-28 01:43:21

What is the correct way to use async/await in "Repository-Service-Controller" architecture?

Hello. There is a wrapper class BaseResponseDataModel. In the controller, the method from the service is called as follows

public async Task<BaseResponseDataModel<List<Item>>> GetLatest(int num)
  {
       var items = await _IItemsService.GetLatestAsync(num);
       return new BaseResponseDataModel<List<Item>>(true, items.Data);
   }

The service looks like this:
public Task<BaseResponseDataModel<List<Item>>> GetLatestAsync(int num)
        {
           //... logic here
            var items =  _itemsRepository.GetItems(num);
           return  new BaseResponseDataModel<List<Item>>(true, items.ToList());
        }

Respectively the repository
public Item[] GetItems(int num)
        {
            return _db.Items.OrderByDescending(x => x.CreatedDate).Take(num).ToArray();
        }

Of course, there is a compilation error in the service on return, since it wants me to add async in the declaration. So here I am new to async methods. Should my repository also be async? Or how should I work in a service method? Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kovalsky, 2019-01-28
@M-Misha-M

The GetLatestAsync method promises to return a Task, but returns an object. declare it asynchronous (async).
The fact that you do not call inside an asynchronous method - asynchronous any other methods is certainly bad, but not fatal.
What are the solutions?
1) Your repository must work asynchronously (if you use EF - it has all the necessary methods. If you use ADO.NET - it depends on the .NET version. You can connect Dapper and the repository will also become asynchronous)
2) remove async / await from the declaration of the GetLatestAsync method . Let's just return the model, not Task<Model>. Again - your interface promises one thing and does another. If there is no asynchrony inside the implementation - how did you declare it? For the future? Then see item 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question