Answer the question
In order to leave comments, you need to log in
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);
}
public Task<BaseResponseDataModel<List<Item>>> GetLatestAsync(int num)
{
//... logic here
var items = _itemsRepository.GetItems(num);
return new BaseResponseDataModel<List<Item>>(true, items.ToList());
}
public Item[] GetItems(int num)
{
return _db.Items.OrderByDescending(x => x.CreatedDate).Take(num).ToArray();
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question