Q46Explain DI and service lifetimes
What is dependency injection?
Dependency injection supplies a class's dependencies from outside instead of constructing them internally. ASP.NET Core has a built-in service container.
Answer
Dependency injection supplies a class's dependencies from outside instead of constructing them internally. ASP.NET Core has a built-in service container.
DI improves testability and separates construction from business logic.
Syntax
builder.Services.AddScoped<IProductService, ProductService>();
public ProductsController(IProductService service) { _service = service; }
Example
DI improves testability and separates construction from business logic.
Code example
builder.Services.AddScoped<IProductService, ProductService>();
public ProductsController(IProductService service) { _service = service; }
Diagram
Explain DI and service lifetimes → implementation → result
Key Points
- Transient creates each resolution
- scoped is one per request scope
- singleton is one per container.
Q47Choose DI lifetimes
Compare transient, scoped, and singleton lifetimes.
Transient creates a new instance each time it is requested; scoped creates one instance per scope, typically an HTTP request; singleton lives for the servi
Answer
Transient creates a new instance each time it is requested; scoped creates one instance per scope, typically an HTTP request; singleton lives for the service provider's lifetime.
DbContext is normally scoped. Do not inject a scoped service directly into a singleton.
Syntax
services.AddTransient<IFormatter, Formatter>();
services.AddScoped<IOrderService, OrderService>();
services.AddSingleton<IClock, SystemClock>();
Example
DbContext is normally scoped. Do not inject a scoped service directly into a singleton.
Code example
services.AddTransient<IFormatter, Formatter>();
services.AddScoped<IOrderService, OrderService>();
services.AddSingleton<IClock, SystemClock>();
Diagram
Choose DI lifetimes → implementation → result
Key Points
- A singleton must be thread-safe if used concurrently.
Q48Diagnose a lifetime mismatch
What is a captive dependency?
A captive dependency occurs when a long-lived service captures a shorter-lived dependency, such as a singleton holding a scoped DbContext. This can cause s
Answer
A captive dependency occurs when a long-lived service captures a shorter-lived dependency, such as a singleton holding a scoped DbContext. This can cause stale state or incorrect cross-request sharing.
Use IServiceScopeFactory to create a scope for bounded work when appropriate, or align the lifetimes.
Syntax
// Avoid: singleton service -> scoped DbContext
services.AddSingleton<ReportService>();
Example
Use IServiceScopeFactory to create a scope for bounded work when appropriate, or align the lifetimes.
Code example
// Avoid: singleton service -> scoped DbContext
services.AddSingleton<ReportService>();
Diagram
Diagnose a lifetime mismatch → implementation → result
Key Points
- Enable scope validation in development to catch common mistakes.
Q49Bind configuration to typed settings
What is the options pattern?
The options pattern binds configuration to a typed class and supports validation and different lifetimes through IOptions, IOptionsSnapshot, and IOptionsMo
Answer
The options pattern binds configuration to a typed class and supports validation and different lifetimes through IOptions, IOptionsSnapshot, and IOptionsMonitor.
Use strongly typed options rather than scattering configuration string keys.
Syntax
builder.Services.AddOptions<MailOptions>()
.BindConfiguration("Mail")
.ValidateDataAnnotations()
.ValidateOnStart();
Example
Use strongly typed options rather than scattering configuration string keys.
Code example
builder.Services.AddOptions<MailOptions>()
.BindConfiguration("Mail")
.ValidateDataAnnotations()
.ValidateOnStart();
Diagram
Bind configuration to typed settings → implementation → result
Key Points
- IOptionsSnapshot is scoped
- IOptionsMonitor supports change notifications.
Q50Describe configuration providers
How does configuration work in ASP.NET Core?
Configuration can come from JSON files, environment variables, command-line arguments, secret stores, and custom providers. Later providers can override ea
Answer
Configuration can come from JSON files, environment variables, command-line arguments, secret stores, and custom providers. Later providers can override earlier values according to provider ordering.
Keep production secrets out of committed appsettings.json; use environment variables or a secret manager.
Syntax
var connection = builder.Configuration.GetConnectionString("Default");
Example
Keep production secrets out of committed appsettings.json; use environment variables or a secret manager.
Code example
var connection = builder.Configuration.GetConnectionString("Default");
Diagram
Describe configuration providers → implementation → result
Key Points
- Configuration key names are commonly hierarchical, e.g. Mail:Host.
Q51Compare configuration sources
What is the difference between appsettings.json and environment variables?
appsettings.json provides baseline settings. Environment variables are useful for deployment-specific overrides and secret injection by the hosting platfor
Answer
appsettings.json provides baseline settings. Environment variables are useful for deployment-specific overrides and secret injection by the hosting platform.
Double underscore commonly maps to a colon in hierarchical configuration keys.
Syntax
ConnectionStrings__Default="Server=...;Database=..."
Example
Double underscore commonly maps to a colon in hierarchical configuration keys.
Code example
ConnectionStrings__Default="Server=...;Database=..."
Diagram
Compare configuration sources → implementation → result
Key Points
- Protect environment variables and logs
- they are not inherently a secret vault.
Q52Build centralized error handling
How do you implement global exception handling?
Use exception-handling middleware or IExceptionHandler to map unexpected exceptions to consistent ProblemDetails responses. Log details internally and avoi
Answer
Use exception-handling middleware or IExceptionHandler to map unexpected exceptions to consistent ProblemDetails responses. Log details internally and avoid exposing stack traces to clients.
Return safe error messages with a trace identifier for support.
Syntax
app.UseExceptionHandler();
// Configure ProblemDetails services as appropriate for the target .NET version.
Example
Return safe error messages with a trace identifier for support.
Code example
app.UseExceptionHandler();
// Configure ProblemDetails services as appropriate for the target .NET version.
Diagram
Build centralized error handling → implementation → result
Key Points
- Do not expose connection strings, SQL text, or stack traces in production responses.
Q53Standardize API errors
What is ProblemDetails?
ProblemDetails is a standard representation for HTTP API errors, with fields such as type, title, status, detail, and instance. ASP.NET Core can generate i
Answer
ProblemDetails is a standard representation for HTTP API errors, with fields such as type, title, status, detail, and instance. ASP.NET Core can generate it for common error responses.
Use stable machine-readable error codes or extensions where clients need programmatic handling.
Syntax
return Problem(title: "Product not found", statusCode: 404);
Example
Use stable machine-readable error codes or extensions where clients need programmatic handling.
Code example
return Problem(title: "Product not found", statusCode: 404);
Diagram
Standardize API errors → implementation → result
Key Points
- Do not put sensitive internal exception details in detail.
Q54Explain binding HTTP data to parameters
What is model binding?
Model binding maps route values, query strings, headers, and request bodies to action parameters or model properties. Validation runs after binding for sup
Answer
Model binding maps route values, query strings, headers, and request bodies to action parameters or model properties. Validation runs after binding for supported models.
Use explicit binding attributes when the source should be clear.
Syntax
public IActionResult Search([FromQuery] string term, [FromQuery] int page = 1)
Example
Use explicit binding attributes when the source should be clear.
Code example
public IActionResult Search([FromQuery] string term, [FromQuery] int page = 1)
Diagram
Explain binding HTTP data to parameters → implementation → result
Key Points
- A request body is normally read once
- avoid multiple body-bound parameters.
Q55Validate request DTOs
How does model validation work?
Validation uses attributes such as [Required], [Range], and custom validators. With [ApiController], invalid model state normally produces an automatic 400
Answer
Validation uses attributes such as [Required], [Range], and custom validators. With [ApiController], invalid model state normally produces an automatic 400 response.
Validation is not a substitute for authorization or business-rule checks.
Syntax
public sealed class CreateProductRequest {
[Required, StringLength(100)] public string Name { get; init; } = "";
[Range(0.01, 100000)] public decimal Price { get; init; }
}
Example
Validation is not a substitute for authorization or business-rule checks.
Code example
public sealed class CreateProductRequest {
[Required, StringLength(100)] public string Name { get; init; } = "";
[Range(0.01, 100000)] public decimal Price { get; init; }
}
Diagram
Validate request DTOs → implementation → result
Key Points
- Validate domain invariants in the domain/application layer as well.
Q56Choose controller return types
What is the difference between IActionResult and ActionResult<T>?
IActionResult can represent many HTTP responses. ActionResult<T> combines a typed success result with alternative IActionResult responses and improves API
Answer
IActionResult can represent many HTTP responses. ActionResult<T> combines a typed success result with alternative IActionResult responses and improves API metadata.
Use typed results where they improve API clarity and OpenAPI generation.
Syntax
public ActionResult<ProductDto> Get(int id) {
var item = Find(id);
return item is null ? NotFound() : Ok(item);
}
Example
Use typed results where they improve API clarity and OpenAPI generation.
Code example
public ActionResult<ProductDto> Get(int id) {
var item = Find(id);
return item is null ? NotFound() : Ok(item);
}
Diagram
Choose controller return types → implementation → result
Key Points
- Minimal APIs use IResult and typed result helpers.
Q57Separate API contracts from persistence models
How do you design DTOs?
DTOs define what the API accepts or returns. They avoid exposing database entities directly and let the API evolve without leaking internal persistence det
Answer
DTOs define what the API accepts or returns. They avoid exposing database entities directly and let the API evolve without leaking internal persistence details.
Use separate input and output DTOs when their rules differ.
Syntax
public record ProductDto(int Id, string Name, decimal Price);
public record CreateProductRequest(string Name, decimal Price);
Example
Use separate input and output DTOs when their rules differ.
Code example
public record ProductDto(int Id, string Name, decimal Price);
public record CreateProductRequest(string Name, decimal Price);
Diagram
Separate API contracts from persistence models → implementation → result
Key Points
- Never rely on hiding sensitive entity properties only in the UI.
Q58Explain EF Core
What is Entity Framework Core?
EF Core is an object-relational mapper that lets .NET code query and update relational databases using entity classes and LINQ. It translates supported que
Answer
EF Core is an object-relational mapper that lets .NET code query and update relational databases using entity classes and LINQ. It translates supported queries to provider-specific SQL.
Use migrations to manage schema changes and inspect generated SQL for important queries.
Syntax
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(connectionString));
Example
Use migrations to manage schema changes and inspect generated SQL for important queries.
Code example
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(connectionString));
Diagram
Explain EF Core → implementation → result
Key Points
- EF Core is not a database
- it uses a provider to connect to one.
Q59Explain unit-of-work behavior
What is DbContext and why is it scoped?
DbContext represents a session with the database and tracks changes to entities. It is designed for a short unit of work and is not thread-safe.
Answer
DbContext represents a session with the database and tracks changes to entities. It is designed for a short unit of work and is not thread-safe.
Do not share one DbContext across concurrent tasks or unrelated requests.
Syntax
await using var db = await factory.CreateDbContextAsync();
Example
Do not share one DbContext across concurrent tasks or unrelated requests.
Code example
await using var db = await factory.CreateDbContextAsync();
Diagram
Explain unit-of-work behavior → implementation → result
Key Points
- A scoped DbContext is the common web-app registration.
Q60Explain tracked entities
What is change tracking in EF Core?
EF Core tracks entity states such as Added, Modified, Deleted, and Unchanged. SaveChanges generates database commands based on those states.
Answer
EF Core tracks entity states such as Added, Modified, Deleted, and Unchanged. SaveChanges generates database commands based on those states.
AsNoTracking is useful for read-only queries where tracking is unnecessary.
Syntax
var product = await db.Products.FindAsync(id);
product!.Price = 19.99m;
await db.SaveChangesAsync();
Example
AsNoTracking is useful for read-only queries where tracking is unnecessary.
Code example
var product = await db.Products.FindAsync(id);
product!.Price = 19.99m;
await db.SaveChangesAsync();
Diagram
Explain tracked entities → implementation → result
Key Points
- Tracked entity changes are not persisted until SaveChanges succeeds.
Q61Compare navigation loading strategies
What is eager, explicit, and lazy loading?
Eager loading fetches related data as part of the query using Include. Explicit loading fetches it on demand. Lazy loading loads navigation data when acces
Answer
Eager loading fetches related data as part of the query using Include. Explicit loading fetches it on demand. Lazy loading loads navigation data when accessed if configured.
Prefer deliberate loading to avoid N+1 query problems.
Syntax
var orders = await db.Orders.Include(o => o.Items).ToListAsync();
Example
Prefer deliberate loading to avoid N+1 query problems.
Code example
var orders = await db.Orders.Include(o => o.Items).ToListAsync();
Diagram
Compare navigation loading strategies → implementation → result
Key Points
- Lazy loading can hide database round trips inside property access.
Q62Detect inefficient data access
What is the N+1 query problem?
N+1 occurs when one query loads a set of rows and then an additional query runs for each row to load related data. It increases latency and database load.
Answer
N+1 occurs when one query loads a set of rows and then an additional query runs for each row to load related data. It increases latency and database load.
Project only the fields needed, use Include when appropriate, and inspect SQL logs or tracing.
Syntax
// Prefer Include/projection instead of querying children inside a loop.
Example
Project only the fields needed, use Include when appropriate, and inspect SQL logs or tracing.
Code example
// Prefer Include/projection instead of querying children inside a loop.
Diagram
Detect inefficient data access → implementation → result
Key Points
- More joins are not always better
- verify query shape and result size.
Q63Manage database schema changes
What are EF Core migrations?
Migrations record incremental schema changes based on model differences. They can be reviewed and applied in controlled deployment processes.
Answer
Migrations record incremental schema changes based on model differences. They can be reviewed and applied in controlled deployment processes.
Review generated migrations before applying them to production.
Syntax
dotnet ef migrations add AddProductSku
dotnet ef database update
Example
Review generated migrations before applying them to production.
Code example
dotnet ef migrations add AddProductSku
dotnet ef database update
Diagram
Manage database schema changes → implementation → result
Key Points
- Coordinate schema changes with application rollout and rollback strategy.
Q64Use parameterized database access
How do you prevent SQL injection?
SQL injection happens when untrusted input is concatenated into SQL syntax. Use parameterized queries or EF Core LINQ; avoid building SQL by string concate
Answer
SQL injection happens when untrusted input is concatenated into SQL syntax. Use parameterized queries or EF Core LINQ; avoid building SQL by string concatenation.
For raw SQL, use parameterized APIs and never interpolate untrusted values as SQL syntax.
Syntax
var product = await db.Products.FirstOrDefaultAsync(p => p.Id == id);
Example
For raw SQL, use parameterized APIs and never interpolate untrusted values as SQL syntax.
Code example
var product = await db.Products.FirstOrDefaultAsync(p => p.Id == id);
Diagram
Use parameterized database access → implementation → result
Key Points
- Parameters represent values, not table or column identifiers.
Q65Explain query evaluation timing
What is LINQ deferred execution?
Many LINQ queries build an iterator or expression and run only when enumerated. Operators such as ToList, ToArray, Count, or foreach trigger execution.
Answer
Many LINQ queries build an iterator or expression and run only when enumerated. Operators such as ToList, ToArray, Count, or foreach trigger execution.
A deferred query can observe later changes to the source collection and may execute more than once.
Syntax
var query = numbers.Where(n => n > 10); // not necessarily evaluated yet
var results = query.ToList();
Example
A deferred query can observe later changes to the source collection and may execute more than once.
Code example
var query = numbers.Where(n => n > 10); // not necessarily evaluated yet
var results = query.ToList();
Diagram
Explain query evaluation timing → implementation → result
Key Points
- IQueryable may execute a database query each time it is enumerated.
Q66Compare LINQ abstractions
What is the difference between IEnumerable and IQueryable?
IEnumerable represents in-memory or streamed enumeration using delegates. IQueryable carries an expression tree that a provider may translate, for example
Answer
IEnumerable represents in-memory or streamed enumeration using delegates. IQueryable carries an expression tree that a provider may translate, for example into SQL.
Keep filtering and projection server-side until the required data has been narrowed.
Syntax
IQueryable<Product> q = db.Products.Where(p => p.Price > 10);
var result = await q.ToListAsync();
Example
Keep filtering and projection server-side until the required data has been narrowed.
Code example
IQueryable<Product> q = db.Products.Where(p => p.Price > 10);
var result = await q.ToListAsync();
Diagram
Compare LINQ abstractions → implementation → result
Key Points
- Calling AsEnumerable changes subsequent operators to client-side LINQ.
Q67Improve I/O scalability
What is async I/O and why use it in APIs?
Asynchronous I/O lets request threads return to the pool while waiting on network, database, or file operations. It improves scalability under I/O load but
Answer
Asynchronous I/O lets request threads return to the pool while waiting on network, database, or file operations. It improves scalability under I/O load but does not make CPU-heavy work faster by itself.
Use async database and HTTP APIs end-to-end and pass cancellation tokens.
Syntax
var product = await db.Products.FindAsync(id, cancellationToken);
Example
Use async database and HTTP APIs end-to-end and pass cancellation tokens.
Code example
var product = await db.Products.FindAsync(id, cancellationToken);
Diagram
Improve I/O scalability → implementation → result
Key Points
- Avoid .Result and .Wait in request paths because they block threads and can cause starvation.
Q68Use Task-returning async methods
Why should async void be avoided?
async void cannot be awaited by callers and its exceptions cannot be observed through a returned Task. It is generally reserved for event handlers.
Answer
async void cannot be awaited by callers and its exceptions cannot be observed through a returned Task. It is generally reserved for event handlers.
Return Task or Task<T> from asynchronous service methods.
Syntax
public async Task SaveAsync() { await repository.SaveAsync(); }
Example
Return Task or Task<T> from asynchronous service methods.
Code example
public async Task SaveAsync() { await repository.SaveAsync(); }
Diagram
Use Task-returning async methods → implementation → result
Key Points
- Fire-and-forget work needs deliberate lifetime, error handling, and observability.
Q69Support cooperative cancellation
What is CancellationToken?
CancellationToken communicates a cancellation request. APIs should pass it through to database, HTTP, and other operations when supported.
Answer
CancellationToken communicates a cancellation request. APIs should pass it through to database, HTTP, and other operations when supported.
Use HttpContext.RequestAborted for work tied to a client request where appropriate.
Syntax
public Task<Product?> GetAsync(int id, CancellationToken ct) => db.Products.FirstOrDefaultAsync(p => p.Id == id, ct);
Example
Use HttpContext.RequestAborted for work tied to a client request where appropriate.
Code example
public Task<Product?> GetAsync(int id, CancellationToken ct) => db.Products.FirstOrDefaultAsync(p => p.Id == id, ct);
Diagram
Support cooperative cancellation → implementation → result
Key Points
- Cancellation is cooperative
- a token does not forcibly stop arbitrary code.
Q70Explain continuation context
What is ConfigureAwait(false)?
ConfigureAwait(false) tells an await not to require resuming on the captured synchronization context. It can matter in reusable libraries, while ASP.NET Co
Answer
ConfigureAwait(false) tells an await not to require resuming on the captured synchronization context. It can matter in reusable libraries, while ASP.NET Core generally has no classic request synchronization context.
Use based on library/runtime context and team conventions rather than applying mechanically everywhere.
Syntax
await operation.ConfigureAwait(false);
Example
Use based on library/runtime context and team conventions rather than applying mechanically everywhere.
Code example
await operation.ConfigureAwait(false);
Diagram
Explain continuation context → implementation → result
Key Points
- It does not mean run on a new thread.
Q71Use HttpClientFactory
How do you call another API with HttpClient?
Use IHttpClientFactory or a typed client to manage HttpClient instances and configuration. Set timeouts, cancellation, and resilient handling appropriate t
Answer
Use IHttpClientFactory or a typed client to manage HttpClient instances and configuration. Set timeouts, cancellation, and resilient handling appropriate to the downstream service.
Use typed clients for a clear contract and central configuration.
Diagram / flow:
builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new Uri("https://inventory.example/"));
var response = await client.GetAsync("api/stock", ct);
response.EnsureSuccessStatusCode();
Syntax
builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new Uri("https://inventory.example/"));
var response = await client.GetAsync("api/stock", ct);
response.EnsureSuccessStatusCode();
Example
Use typed clients for a clear contract and central configuration.
Code example
builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new Uri("https://inventory.example/"));
var response = await client.GetAsync("api/stock", ct);
response.EnsureSuccessStatusCode();
Diagram
Diagram / flow:
builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new Uri("https://inventory.example/"));
var response = await client.GetAsync("api/stock", ct);
response.EnsureSuccessStatusCode();
Key Points
- Do not create and dispose a new HttpClient for every request.
Q72Add resilient HTTP policies
How do you configure retries for HTTP calls?
Retries can help with transient failures, but should be bounded, use backoff and jitter, and respect idempotency and server guidance. Modern .NET resilienc
Answer
Retries can help with transient failures, but should be bounded, use backoff and jitter, and respect idempotency and server guidance. Modern .NET resilience handlers can be registered through supported resilience packages.
Avoid retrying non-idempotent operations blindly; consider Retry-After and an overall timeout.
Diagram / flow:
// Register a supported resilience handler for the named/typed HttpClient.
Syntax
// Register a supported resilience handler for the named/typed HttpClient.
Example
Avoid retrying non-idempotent operations blindly; consider Retry-After and an overall timeout.
Code example
// Register a supported resilience handler for the named/typed HttpClient.
Diagram
Diagram / flow:
// Register a supported resilience handler for the named/typed HttpClient.
Key Points
- Retries can amplify an outage if used without limits.
Q73Explain method semantics
What are REST HTTP methods and idempotency?
GET is safe and idempotent by convention; PUT and DELETE are idempotent in intended effect; POST is generally not idempotent. PATCH applies partial modific
Answer
GET is safe and idempotent by convention; PUT and DELETE are idempotent in intended effect; POST is generally not idempotent. PATCH applies partial modifications and its idempotency depends on the operation.
Design create/payment endpoints with idempotency keys when clients may retry.
Syntax
PUT /api/products/42
DELETE /api/products/42
Example
Design create/payment endpoints with idempotency keys when clients may retry.
Code example
PUT /api/products/42
DELETE /api/products/42
Diagram
Explain method semantics → implementation → result
Key Points
- Idempotency describes effect, not whether the same response body is returned.
Q74Choose status codes
Which HTTP status codes should an API use?
Common codes include 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable
Answer
Common codes include 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Content where adopted, and 500 Internal Server Error.
Use 401 when authentication is missing/invalid and 403 when the authenticated caller lacks permission.
Syntax
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
Example
Use 401 when authentication is missing/invalid and 403 when the authenticated caller lacks permission.
Code example
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
Diagram
Choose status codes → implementation → result
Key Points
- Be consistent and document error contracts.
Q75Distinguish identity from permissions
What is authentication versus authorization?
Authentication establishes who the caller is. Authorization determines what the caller is allowed to do.
Answer
Authentication establishes who the caller is. Authorization determines what the caller is allowed to do.
Use policies and roles/claims to enforce access to endpoints and resources.
Syntax
builder.Services.AddAuthentication().AddJwtBearer();
app.UseAuthentication();
app.UseAuthorization();
Example
Use policies and roles/claims to enforce access to endpoints and resources.
Code example
builder.Services.AddAuthentication().AddJwtBearer();
app.UseAuthentication();
app.UseAuthorization();
Diagram
Distinguish identity from permissions → implementation → result
Key Points
- A valid token does not automatically authorize every action.
Q76Explain JSON Web Tokens
What is JWT?
A JWT is a compact token format that can carry claims and is often signed. APIs validate signature, issuer, audience, and lifetime before trusting claims.
Answer
A JWT is a compact token format that can carry claims and is often signed. APIs validate signature, issuer, audience, and lifetime before trusting claims.
Never put secrets in JWT payloads; signed JWT payloads are typically readable.
Syntax
Authorization: Bearer <access-token>
Example
Never put secrets in JWT payloads; signed JWT payloads are typically readable.
Code example
Authorization: Bearer <access-token>
Diagram
Explain JSON Web Tokens → implementation → result
Key Points
- JWT is a token format, not an authentication protocol by itself.
Q77Compare delegated authorization and identity
What is OAuth 2.0 and OpenID Connect?
OAuth 2.0 is an authorization framework for delegated access. OpenID Connect adds an identity layer on top of OAuth 2.0. APIs typically validate access tok
Answer
OAuth 2.0 is an authorization framework for delegated access. OpenID Connect adds an identity layer on top of OAuth 2.0. APIs typically validate access tokens; clients use OIDC for sign-in.
Use Authorization Code with PKCE for interactive public clients and a trusted identity provider.
Syntax
// Configure the appropriate OIDC/OAuth provider and validate tokens server-side.
Example
Use Authorization Code with PKCE for interactive public clients and a trusted identity provider.
Code example
// Configure the appropriate OIDC/OAuth provider and validate tokens server-side.
Diagram
Compare delegated authorization and identity → implementation → result
Key Points
- Do not implement token validation by merely decoding the token.
Q78Protect endpoints with policies
How do you implement role or policy authorization?
Define authorization policies and apply them to endpoints or controllers. Policies can evaluate roles, claims, and custom requirements.
Answer
Define authorization policies and apply them to endpoints or controllers. Policies can evaluate roles, claims, and custom requirements.
Policies centralize access rules and can be unit tested.
Syntax
builder.Services.AddAuthorization(o => o.AddPolicy("CanManageProducts", p => p.RequireRole("Admin")));
[Authorize(Policy = "CanManageProducts")]
Example
Policies centralize access rules and can be unit tested.
Code example
builder.Services.AddAuthorization(o => o.AddPolicy("CanManageProducts", p => p.RequireRole("Admin")));
[Authorize(Policy = "CanManageProducts")]
Diagram
Protect endpoints with policies → implementation → result
Key Points
- Resource ownership often requires checking the specific resource, not just a broad role.
Q79Explain cross-origin requests
What is CORS?
Cross-Origin Resource Sharing is a browser-enforced mechanism controlled by response headers that determines whether a web page from another origin can rea
Answer
Cross-Origin Resource Sharing is a browser-enforced mechanism controlled by response headers that determines whether a web page from another origin can read a response.
Allow only trusted origins and configure credentials carefully.
Syntax
builder.Services.AddCors(o => o.AddPolicy("Frontend", p => p.WithOrigins("https://app.example.com").AllowAnyHeader().AllowAnyMethod()));
Example
Allow only trusted origins and configure credentials carefully.
Code example
builder.Services.AddCors(o => o.AddPolicy("Frontend", p => p.WithOrigins("https://app.example.com").AllowAnyHeader().AllowAnyMethod()));
Diagram
Explain cross-origin requests → implementation → result
Key Points
- CORS is not an API authentication mechanism and does not block non-browser clients.
Q80Manage application secrets
How do you secure secrets in ASP.NET Core?
Use development user secrets locally and a managed secret store or platform-provided secure configuration in production. Rotate credentials and restrict ac
Answer
Use development user secrets locally and a managed secret store or platform-provided secure configuration in production. Rotate credentials and restrict access.
Avoid committing secrets, printing them in logs, or embedding them in frontend code.
Syntax
dotnet user-secrets init
dotnet user-secrets set "Mail:ApiKey" "local-development-value"
Example
Avoid committing secrets, printing them in logs, or embedding them in frontend code.
Code example
dotnet user-secrets init
dotnet user-secrets set "Mail:ApiKey" "local-development-value"
Diagram
Manage application secrets → implementation → result
Key Points
- Environment variables are a delivery mechanism, not always a full secret-management solution.
Q81Explain repository abstraction
What is the repository pattern?
A repository presents a collection-like interface for domain persistence and can isolate complex data access. EF Core DbContext already provides repository
Answer
A repository presents a collection-like interface for domain persistence and can isolate complex data access. EF Core DbContext already provides repository/unit-of-work-like behavior, so an extra layer should add value.
Use repositories when they clarify domain boundaries or isolate persistence, not automatically for every DbSet.
Syntax
public interface IProductRepository { Task<Product?> GetAsync(int id, CancellationToken ct); }
Example
Use repositories when they clarify domain boundaries or isolate persistence, not automatically for every DbSet.
Code example
public interface IProductRepository { Task<Product?> GetAsync(int id, CancellationToken ct); }
Diagram
Explain repository abstraction → implementation → result
Key Points
- Avoid generic repositories that hide useful EF Core query capabilities.
Q82Coordinate persistence changes
What is the Unit of Work pattern?
A Unit of Work coordinates changes and commits them together. EF Core DbContext tracks changes and SaveChanges normally acts as the unit-of-work commit bou
Answer
A Unit of Work coordinates changes and commits them together. EF Core DbContext tracks changes and SaveChanges normally acts as the unit-of-work commit boundary.
A single SaveChanges call usually wraps its commands in a transaction when supported by the provider.
Syntax
db.Products.Add(product);
db.AuditEntries.Add(entry);
await db.SaveChangesAsync(ct);
Example
A single SaveChanges call usually wraps its commands in a transaction when supported by the provider.
Code example
db.Products.Add(product);
db.AuditEntries.Add(entry);
await db.SaveChangesAsync(ct);
Diagram
Coordinate persistence changes → implementation → result
Key Points
- External systems such as email are not automatically included in the database transaction.
Q83Explain ACID transactions
What is a database transaction?
A transaction groups operations into an all-or-nothing unit. ACID refers to atomicity, consistency, isolation, and durability.
Answer
A transaction groups operations into an all-or-nothing unit. ACID refers to atomicity, consistency, isolation, and durability.
Keep transactions short and handle rollback/disposal correctly.
Syntax
await using var tx = await db.Database.BeginTransactionAsync(ct);
// perform operations
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
Example
Keep transactions short and handle rollback/disposal correctly.
Code example
await using var tx = await db.Database.BeginTransactionAsync(ct);
// perform operations
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
Diagram
Explain ACID transactions → implementation → result
Key Points
- A transaction cannot by itself make a distributed database and external API call atomic.
Q84Prevent lost updates
How do you handle concurrency in EF Core?
Optimistic concurrency detects when a row changed since it was read, often using a rowversion or concurrency token. SaveChanges can throw DbUpdateConcurren
Answer
Optimistic concurrency detects when a row changed since it was read, often using a rowversion or concurrency token. SaveChanges can throw DbUpdateConcurrencyException.
Catch concurrency exceptions and choose a policy: reload, merge, reject, or retry safely.
Syntax
public class Product { public int Id { get; set; } [Timestamp] public byte[] RowVersion { get; set; } = []; }
Example
Catch concurrency exceptions and choose a policy: reload, merge, reject, or retry safely.
Code example
public class Product { public int Id { get; set; } [Timestamp] public byte[] RowVersion { get; set; } = []; }
Diagram
Prevent lost updates → implementation → result
Key Points
- A retry must re-evaluate business rules using fresh data.
Q85Explain indexes and query performance
What is a database index?
An index helps the database locate rows without scanning the entire table, but it consumes storage and adds write overhead. Index columns should reflect ac
Answer
An index helps the database locate rows without scanning the entire table, but it consumes storage and adds write overhead. Index columns should reflect actual query patterns.
Inspect execution plans and query metrics before adding indexes.
Syntax
modelBuilder.Entity<Product>().HasIndex(p => p.Sku).IsUnique();
Example
Inspect execution plans and query metrics before adding indexes.
Code example
modelBuilder.Entity<Product>().HasIndex(p => p.Sku).IsUnique();
Diagram
Explain indexes and query performance → implementation → result
Key Points
- Composite index column order affects which query predicates can use it efficiently.
Q86Page API results safely
What is pagination and how do you implement it?
Pagination limits response size. Offset pagination is simple; keyset pagination is often more efficient for large or frequently changing datasets.
Answer
Pagination limits response size. Offset pagination is simple; keyset pagination is often more efficient for large or frequently changing datasets.
Validate page and pageSize, cap maximum page size, and use deterministic ordering.
Syntax
var items = await db.Products.OrderBy(p => p.Id).Skip((page-1)*pageSize).Take(pageSize).ToListAsync(ct);
Example
Validate page and pageSize, cap maximum page size, and use deterministic ordering.
Code example
var items = await db.Products.OrderBy(p => p.Id).Skip((page-1)*pageSize).Take(pageSize).ToListAsync(ct);
Diagram
Page API results safely → implementation → result
Key Points
- For large datasets, consider a cursor based on the last ordered key.
Q87Compare memory and distributed cache
What is caching in ASP.NET Core?
Caching stores reusable data to reduce latency or backend load. IMemoryCache is local to one process; distributed caches such as Redis can be shared across
Answer
Caching stores reusable data to reduce latency or backend load. IMemoryCache is local to one process; distributed caches such as Redis can be shared across instances.
Choose expiration and invalidation deliberately; avoid caching user-specific data under shared keys.
Syntax
builder.Services.AddMemoryCache();
cache.Set("product:42", product, TimeSpan.FromMinutes(5));
Example
Choose expiration and invalidation deliberately; avoid caching user-specific data under shared keys.
Code example
builder.Services.AddMemoryCache();
cache.Set("product:42", product, TimeSpan.FromMinutes(5));
Diagram
Compare memory and distributed cache → implementation → result
Key Points
- A cache is not the source of truth and may be stale.
Q88Cache HTTP responses
What is output caching?
Output caching stores generated responses according to configured policies. It is useful for responses that can safely be reused across requests.
Answer
Output caching stores generated responses according to configured policies. It is useful for responses that can safely be reused across requests.
Apply policies only to cacheable endpoints and account for authorization, vary-by parameters, and invalidation.
Syntax
builder.Services.AddOutputCache();
app.UseOutputCache();
Example
Apply policies only to cacheable endpoints and account for authorization, vary-by parameters, and invalidation.
Code example
builder.Services.AddOutputCache();
app.UseOutputCache();
Diagram
Cache HTTP responses → implementation → result
Key Points
- Do not cache sensitive personalized responses publicly.
Q89Use structured logging
What is logging with ILogger<T>?
ILogger provides category-based structured logging with levels such as Trace, Debug, Information, Warning, Error, and Critical. Structured properties are e
Answer
ILogger provides category-based structured logging with levels such as Trace, Debug, Information, Warning, Error, and Critical. Structured properties are easier to query than concatenated strings.
Use scopes or correlation IDs to connect events across a request.
Syntax
logger.LogInformation("Created product {ProductId}", product.Id);
Example
Use scopes or correlation IDs to connect events across a request.
Code example
logger.LogInformation("Created product {ProductId}", product.Id);
Diagram
Use structured logging → implementation → result
Key Points
- Never log passwords, access tokens, or sensitive personal data.
Q90Expose application health
What is health checking?
Health checks report whether an app or its dependencies are healthy. Liveness asks whether the process should keep running; readiness asks whether it can a
Answer
Health checks report whether an app or its dependencies are healthy. Liveness asks whether the process should keep running; readiness asks whether it can accept traffic.
Keep liveness checks lightweight; readiness may include critical dependencies.
Syntax
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");
Example
Keep liveness checks lightweight; readiness may include critical dependencies.
Code example
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");
Diagram
Expose application health → implementation → result
Key Points
- Secure detailed health endpoints where they expose internal information.
Q91Document an API contract
What is Swagger/OpenAPI?
OpenAPI describes endpoints, parameters, request/response schemas, and security requirements. Swagger UI can render an interactive documentation page from
Answer
OpenAPI describes endpoints, parameters, request/response schemas, and security requirements. Swagger UI can render an interactive documentation page from an OpenAPI document.
Use DTOs and response metadata to improve generated docs; consider disabling public interactive docs in production.
Syntax
// Register and map OpenAPI/Swagger services according to the target .NET version.
Example
Use DTOs and response metadata to improve generated docs; consider disabling public interactive docs in production.
Code example
// Register and map OpenAPI/Swagger services according to the target .NET version.
Diagram
Document an API contract → implementation → result
Key Points
- OpenAPI documents a contract
- it does not guarantee implementation correctness.
Q92Create endpoints with minimal APIs
What is minimal API in ASP.NET Core?
Minimal APIs define HTTP endpoints with less ceremony than controller classes and support DI, filters, binding, and typed results.
Answer
Minimal APIs define HTTP endpoints with less ceremony than controller classes and support DI, filters, binding, and typed results.
Use route groups and endpoint filters to organize larger APIs.
Syntax
var app = builder.Build();
app.MapGet("/api/ping", () => Results.Ok(new { status = "ok" }));
app.Run();
Example
Use route groups and endpoint filters to organize larger APIs.
Code example
var app = builder.Build();
app.MapGet("/api/ping", () => Results.Ok(new { status = "ok" }));
app.Run();
Diagram
Create endpoints with minimal APIs → implementation → result
Key Points
- Minimal APIs and controllers can coexist in one application.
Q93Explain action and authorization filters
What is a filter in ASP.NET Core MVC?
Filters run at defined stages around MVC request processing. Common kinds include authorization, resource, action, exception, and result filters.
Answer
Filters run at defined stages around MVC request processing. Common kinds include authorization, resource, action, exception, and result filters.
Use middleware for broad HTTP concerns and filters for MVC/action-specific behavior.
Syntax
public sealed class TimingFilter : IAsyncActionFilter { /* measure and call next */ }
Example
Use middleware for broad HTTP concerns and filters for MVC/action-specific behavior.
Code example
public sealed class TimingFilter : IAsyncActionFilter { /* measure and call next */ }
Diagram
Explain action and authorization filters → implementation → result
Key Points
- Filter order affects behavior
- prefer built-in features when available.
Q94Choose the right pipeline extension
What is the difference between middleware and filters?
Middleware operates in the HTTP pipeline and can apply to all requests. MVC filters run inside the MVC action-invocation pipeline and have access to action
Answer
Middleware operates in the HTTP pipeline and can apply to all requests. MVC filters run inside the MVC action-invocation pipeline and have access to action context and model state.
Use middleware for correlation, exception handling, and general request processing; filters for MVC-specific concerns.
Syntax
app.Use(async (ctx, next) => await next());
Example
Use middleware for correlation, exception handling, and general request processing; filters for MVC-specific concerns.
Code example
app.Use(async (ctx, next) => await next());
Diagram
Choose the right pipeline extension → implementation → result
Key Points
- Endpoint filters are also available for minimal APIs.
Q95Map between DTOs and entities
What is AutoMapper and when should you use it?
Object mappers reduce repetitive property-copying code, but mapping rules can hide behavior if overused. Explicit mapping is often clearer for small or sec
Answer
Object mappers reduce repetitive property-copying code, but mapping rules can hide behavior if overused. Explicit mapping is often clearer for small or security-sensitive DTOs.
Use mapping configuration tests and avoid mapping untrusted request objects onto tracked entities blindly.
Syntax
var dto = new ProductDto(entity.Id, entity.Name, entity.Price);
Example
Use mapping configuration tests and avoid mapping untrusted request objects onto tracked entities blindly.
Code example
var dto = new ProductDto(entity.Id, entity.Name, entity.Price);
Diagram
Map between DTOs and entities → implementation → result
Key Points
- Mapping is not validation or authorization.
Q127C#
How does pattern matching simplify conditional logic?
Pattern matching checks an input against type, constant, relational, property, or list patterns. It can make branching more expressive and reduce
Answer
Pattern matching checks an input against type, constant, relational, property, or list patterns. It can make branching more expressive and reduce unsafe casts.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
value switch { int n when n > 0 => "positive", int => "non-positive", _ => "not an integer" }
Example
object value = 12; var label = value switch { int n when n > 0 => "positive", int => "non-positive", _ => "not an integer" };
Code example
object value = 12;\nvar label = value switch\n{\n int n when n > 0 => "positive",\n int => "non-positive",\n _ => "not an integer"\n};
Diagram
Input → pattern checks → first matching arm → result.
Key Points
- Pattern matching checks an input against type, constant, relational, property, or list patterns.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q129C#
How do you dispose asynchronous resources?
Use await using with IAsyncDisposable when cleanup itself requires asynchronous work, such as flushing or closing an asynchronous resource.
Answer
Use await using with IAsyncDisposable when cleanup itself requires asynchronous work, such as flushing or closing an asynchronous resource.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
await using var resource = new AsyncResource();
Example
await using var stream = new FileStream( "data.bin", FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); // use stream; disposal is awaited
Code example
await using var stream = new FileStream(\n "data.bin", FileMode.Open, FileAccess.Read, FileShare.Read,\n bufferSize: 4096, useAsync: true);\n// use stream; disposal is awaited
Diagram
Acquire async resource → perform work → await DisposeAsync during scope exit.
Key Points
- Use await using with IAsyncDisposable when cleanup itself requires asynchronous work, such as flushing or closing an asynchronous resource.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q131OOP
Explain the Liskov Substitution Principle with a practical example.
A subtype should be usable wherever its base abstraction is expected without breaking correctness or documented expectations. Prefer capability-f
Answer
A subtype should be usable wherever its base abstraction is expected without breaking correctness or documented expectations. Prefer capability-focused interfaces when not every subtype supports every operation.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
IReadOnlyCollection<T> exposes reading without requiring mutation.
Example
public interface IReadOnlyShape { double Area(); } public sealed class Circle(double radius) : IReadOnlyShape { public double Area() => Math.PI * radius * radius; }
Code example
public interface IReadOnlyShape { double Area(); }\npublic sealed class Circle(double radius) : IReadOnlyShape\n{ public double Area() => Math.PI * radius * radius; }
Diagram
Client → abstraction contract → any implementation that preserves the contract.
Key Points
- A subtype should be usable wherever its base abstraction is expected without breaking correctness or documented expectations.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q132OOP
How does the Interface Segregation Principle improve design?
Clients should not depend on methods they do not use. Split large interfaces into cohesive capabilities so implementations only take dependencies
Answer
Clients should not depend on methods they do not use. Split large interfaces into cohesive capabilities so implementations only take dependencies on relevant contracts.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
IPrinter.Print(); IScanner.Scan();
Example
public interface IPrinter { void Print(string text); } public interface IScanner { byte[] Scan(); }
Code example
public interface IPrinter { void Print(string text); }\npublic interface IScanner { byte[] Scan(); }
Diagram
Multifunction device → small capability interfaces → focused clients.
Key Points
- Clients should not depend on methods they do not use.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q133OOP
What is the Dependency Inversion Principle?
High-level policy should depend on abstractions rather than concrete low-level details. Both sides depend on a stable contract, with dependency i
Answer
High-level policy should depend on abstractions rather than concrete low-level details. Both sides depend on a stable contract, with dependency injection supplying the implementation.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
OrderService(IOrderRepository repository)
Example
public sealed class OrderService(IOrderRepository repository) { public Task SaveAsync(Order order) => repository.SaveAsync(order); }
Code example
public sealed class OrderService(IOrderRepository repository)\n{\n public Task SaveAsync(Order order) => repository.SaveAsync(order);\n}
Diagram
OrderService → IOrderRepository ← SqlOrderRepository.
Key Points
- High-level policy should depend on abstractions rather than concrete low-level details.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q134ASP.NET Core
Why does middleware order matter in ASP.NET Core?
Middleware executes in registration order on the request path and unwinds in reverse on the response path. Authentication must run before authori
Answer
Middleware executes in registration order on the request path and unwinds in reverse on the response path. Authentication must run before authorization, and endpoint mapping should fit the intended pipeline.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
app.UseAuthentication(); app.UseAuthorization();
Example
app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers();
Code example
app.UseRouting();\napp.UseAuthentication();\napp.UseAuthorization();\napp.MapControllers();
Diagram
Request → routing → authentication → authorization → endpoint → response.
Key Points
- Middleware executes in registration order on the request path and unwinds in reverse on the response path.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q135ASP.NET Core
How do you validate strongly typed configuration with the options pattern?
Bind configuration to a typed options class and validate it during startup. This surfaces invalid configuration early instead of failing during a
Answer
Bind configuration to a typed options class and validate it during startup. This surfaces invalid configuration early instead of failing during a user request.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
services.AddOptions<MailOptions>().BindConfiguration("Mail").ValidateOnStart();
Example
builder.Services.AddOptions<MailOptions>() .BindConfiguration("Mail") .Validate(o => o.Port is > 0 and <= 65535, "Invalid port") .ValidateOnStart();
Code example
builder.Services.AddOptions<MailOptions>()\n .BindConfiguration("Mail")\n .Validate(o => o.Port is > 0 and <= 65535, "Invalid port")\n .ValidateOnStart();
Diagram
appsettings → configuration binding → validation → typed options injected into service.
Key Points
- Bind configuration to a typed options class and validate it during startup.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q136Web API
What is Problem Details in an HTTP API?
Problem Details provides a consistent machine-readable error body with fields such as type, title, status, detail, and instance. Avoid leaking st
Answer
Problem Details provides a consistent machine-readable error body with fields such as type, title, status, detail, and instance. Avoid leaking stack traces or secrets to clients.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
HTTP 400 + application/problem+json
Example
return Results.Problem( title: "Invalid request", detail: "The supplied page size is outside the allowed range.", statusCode: StatusCodes.Status400BadRequest);
Code example
return Results.Problem(\n title: "Invalid request",\n detail: "The supplied page size is outside the allowed range.",\n statusCode: StatusCodes.Status400BadRequest);
Diagram
Request fails → exception/validation handler → normalized Problem Details response.
Key Points
- Problem Details provides a consistent machine-readable error body with fields such as type, title, status, detail, and instance.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q139Dependency Injection
What are keyed services in modern .NET dependency injection?
Keyed services register multiple implementations under distinct keys. Resolve the implementation by key when the choice is explicit and stable; a
Answer
Keyed services register multiple implementations under distinct keys. Resolve the implementation by key when the choice is explicit and stable; avoid turning service location into a general-purpose pattern.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
services.AddKeyedScoped<INotifier, EmailNotifier>("email");
Example
builder.Services.AddKeyedScoped<INotifier, EmailNotifier>("email"); builder.Services.AddKeyedScoped<INotifier, SmsNotifier>("sms"); // Inject with [FromKeyedServices("email")] INotifier notifier
Code example
builder.Services.AddKeyedScoped<INotifier, EmailNotifier>("email");\nbuilder.Services.AddKeyedScoped<INotifier, SmsNotifier>("sms");\n// Inject with [FromKeyedServices("email")] INotifier notifier
Diagram
Registration key → DI container → matching implementation.
Key Points
- Keyed services register multiple implementations under distinct keys.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q141Asynchronous Programming
How should CancellationToken be propagated through async methods?
Accept a CancellationToken, pass it to cancellable downstream APIs, and honor cancellation rather than swallowing OperationCanceledException indi
Answer
Accept a CancellationToken, pass it to cancellable downstream APIs, and honor cancellation rather than swallowing OperationCanceledException indiscriminately. Cancellation is cooperative.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
Task<T> GetAsync(CancellationToken cancellationToken)
Example
public async Task<string> ReadAsync(CancellationToken cancellationToken) { using var response = await client.GetAsync("/data", cancellationToken); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(cancellationToken); }
Code example
public async Task<string> ReadAsync(CancellationToken cancellationToken)\n{\n using var response = await client.GetAsync("/data", cancellationToken);\n response.EnsureSuccessStatusCode();\n return await response.Content.ReadAsStringAsync(cancellationToken);\n}
Diagram
HTTP request cancelled → token propagated → downstream operation stops cooperatively.
Key Points
- Accept a CancellationToken, pass it to cancellable downstream APIs, and honor cancellation rather than swallowing OperationCanceledException indiscriminately.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q142Asynchronous Programming
When should you use Task.WhenAll?
Task.WhenAll waits for multiple tasks and enables independent I/O operations to overlap. It does not create threads by itself, and concurrency sh
Answer
Task.WhenAll waits for multiple tasks and enables independent I/O operations to overlap. It does not create threads by itself, and concurrency should be bounded when many operations are launched.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
await Task.WhenAll(taskA, taskB);
Example
Task<User> userTask = GetUserAsync(id, ct); Task<IReadOnlyList<Order>> ordersTask = GetOrdersAsync(id, ct); await Task.WhenAll(userTask, ordersTask); var result = (await userTask, await ordersTask);
Code example
Task<User> userTask = GetUserAsync(id, ct);\nTask<IReadOnlyList<Order>> ordersTask = GetOrdersAsync(id, ct);\nawait Task.WhenAll(userTask, ordersTask);\nvar result = (await userTask, await ordersTask);
Diagram
Start independent I/O tasks → await all → combine results.
Key Points
- Task.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q145Design Patterns
How does the Strategy pattern help select business rules?
Strategy encapsulates interchangeable algorithms behind a common interface. The caller depends on the abstraction and can select a policy through
Answer
Strategy encapsulates interchangeable algorithms behind a common interface. The caller depends on the abstraction and can select a policy through configuration or DI.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
IDiscountStrategy.Calculate(order)
Example
public interface IDiscountStrategy { decimal Calculate(decimal total); } public sealed class VipDiscount : IDiscountStrategy { public decimal Calculate(decimal total) => total * 0.9m; }
Code example
public interface IDiscountStrategy { decimal Calculate(decimal total); }\npublic sealed class VipDiscount : IDiscountStrategy\n{ public decimal Calculate(decimal total) => total * 0.9m; }
Diagram
Checkout → IDiscountStrategy → selected discount strategy.
Key Points
- Strategy encapsulates interchangeable algorithms behind a common interface.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q146Design Patterns
What is the Decorator pattern and where is it useful?
Decorator wraps an object implementing the same abstraction to add behavior without modifying the wrapped implementation. Common uses include log
Answer
Decorator wraps an object implementing the same abstraction to add behavior without modifying the wrapped implementation. Common uses include logging, caching, metrics, and retries.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
new LoggingRepository(new SqlRepository())
Example
public sealed class LoggingRepository(IRepository inner, ILogger<LoggingRepository> log) : IRepository { public async Task SaveAsync(Item item) { log.LogInformation("Saving item"); await inner.SaveAsync(item); } }
Code example
public sealed class LoggingRepository(IRepository inner, ILogger<LoggingRepository> log) : IRepository\n{\n public async Task SaveAsync(Item item)\n { log.LogInformation("Saving item"); await inner.SaveAsync(item); }\n}
Diagram
Caller → decorator (logging) → underlying repository.
Key Points
- Decorator wraps an object implementing the same abstraction to add behavior without modifying the wrapped implementation.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q147Design Patterns
When is the Factory pattern useful in a .NET application?
A factory centralizes creation when construction is conditional, complex, or depends on runtime input. For simple services, built-in DI registrat
Answer
A factory centralizes creation when construction is conditional, complex, or depends on runtime input. For simple services, built-in DI registration is often enough and a custom factory may be unnecessary.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
IParser parser = parserFactory.Create(format);
Example
public IParser Create(string format) => format switch { "json" => new JsonParser(), "xml" => new XmlParser(), _ => throw new NotSupportedException(format) };
Code example
public IParser Create(string format) => format switch\n{\n "json" => new JsonParser(),\n "xml" => new XmlParser(),\n _ => throw new NotSupportedException(format)\n};
Diagram
Format input → factory selection → matching parser instance.
Key Points
- A factory centralizes creation when construction is conditional, complex, or depends on runtime input.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.
Q150ASP.NET Core
How do readiness and liveness health checks differ?
Liveness indicates whether the process should be restarted; readiness indicates whether it can safely receive traffic. Avoid making liveness depe
Answer
Liveness indicates whether the process should be restarted; readiness indicates whether it can safely receive traffic. Avoid making liveness depend on remote systems, which can cause restart cascades.
Apply the approach according to the application's constraints and verify important behavior with automated tests.
Syntax
MapHealthChecks("/health/ready")
Example
builder.Services.AddHealthChecks(); app.MapHealthChecks("/health/live"); app.MapHealthChecks("/health/ready");
Code example
builder.Services.AddHealthChecks();\napp.MapHealthChecks("/health/live");\napp.MapHealthChecks("/health/ready");
Diagram
Orchestrator checks liveness for restart decisions and readiness for traffic routing.
Key Points
- Liveness indicates whether the process should be restarted; readiness indicates whether it can safely receive traffic.
- Keep dependencies and responsibilities explicit.
- Cover error handling and edge cases in tests.