ASP.NET Core MVC Interview Question #150

What are best practices for services, error handling, logging, caching, and performance in MVC?

Dependency Injection, Services, Error Handling, Logging & Performance Senior Advanced

Quick Interview Answer

Use dependency injection with appropriate lifetimes, keep controllers thin, and put meaningful application workflows in services. Consume configuration through clear options, log structured operational information without secrets, and handle unexpected failures centrally with safe production error pages.

Detailed Explanation

Use dependency injection with appropriate lifetimes, keep controllers thin, and put meaningful application workflows in services. Consume configuration through clear options, log structured operational information without secrets, and handle unexpected failures centrally with safe production error pages.

Use caching only when the data and invalidation strategy justify it, and never leak personalized output through shared caches. Prefer asynchronous I/O, propagate cancellation tokens, project efficient database queries, paginate large datasets, and investigate N+1 queries. Most importantly, profile and measure the application before applying performance optimizations.

Code Example

builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddMemoryCache();
builder.Services.AddOutputCache();

if (!app.Environment.IsDevelopment())
    app.UseExceptionHandler("/Home/Error");

app.UseOutputCache();