ASP.NET apps are organized into classes: controllers, services, repositories, and view models. Methods encapsulate behavior; properties expose state with optional validation.
Controller-shaped class (conceptual)
public class ProductsController {
private readonly IProductService _products;
public ProductsController(IProductService products) {
_products = products;
}
public async Task<IActionResult> Index() {
var list = await _products.GetAllAsync();
return Ok(list);
}
}
Constructor injection is the default pattern—framework resolves dependencies when creating the controller.
Properties vs fields
Prefer auto-properties for DTOs: public string Name { get; set; } = ""; Records (public record UserDto(int Id, string Name);) suit immutable API responses.
Important interview questions and answers
- Q: Why constructor injection?
A: Dependencies are explicit, required, and easy to mock in unit tests. - Q: record vs class for DTOs?
A: Records give value-based equality and concise syntax for read-only data transfer objects.
Self-check
- Where does ASP.NET inject dependencies into a controller?
- When prefer a record over a mutable class?