ASP.NET Core Web API Interview Question #125
What are best practices for services, EF Core, async, and data access in Web APIs?
Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate
Quick Interview Answer
Keep controllers focused on HTTP concerns and place application workflows behind well-defined services. Choose dependency-injection lifetimes carefully, keep DbContext request-scoped, propagate CancellationToken, and use asynchronous I/O for database and network operations.
Detailed Explanation
Keep controllers focused on HTTP concerns and place application workflows behind well-defined services. Choose dependency-injection lifetimes carefully, keep DbContext request-scoped, propagate CancellationToken, and use asynchronous I/O for database and network operations.
For reads, use AsNoTracking and project directly to DTOs where appropriate. Paginate large collections, avoid N+1 queries, inspect important SQL, handle concurrency and persistence failures deliberately, keep transactions short, and use IHttpClientFactory for external HTTP dependencies. Add architectural abstractions such as repositories only when they provide meaningful value.
Code Example
public async Task<ProductResponse?> GetAsync(
int id,
CancellationToken token)
{
return await _db.Products
.AsNoTracking()
.Where(x => x.Id == id)
.Select(x => new ProductResponse
{
Id = x.Id,
Name = x.Name,
Price = x.Price
})
.SingleOrDefaultAsync(token);
}