📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š .NET Interview Questions

1325 questions for senior .NET engineer interviews, each with a 30-second answer, the full answer, a deep dive, the follow-ups interviewers ask next, and real-world production problems.

Enterprise Patterns

Repository, Unit of Work, Service Layer, Domain and Application Services, DTO, Mapper, CQRS, Outbox, Inbox, Saga, Circuit Breaker, Retry and Bulkhead in .NET 10 services.

  1. What is the Repository pattern? Explain its intent, how it differs from a DAO or a table gateway, why a generic IRepository<T> with GetAll, Update and Save over EF Core is often an anti-pattern, and what a good repository interface looks like in a .NET 10 service.

    Repository pattern in .NET: intent (a collection-like abstraction over persistence for an aggregate root), repository vs DAO/table gateway, why a generic IRepository<T> over EF Core leaks IQueryable, breaks the unit of work with per-repository Save, encourages Update() on detached graphs and repositories for child entities, and what a narrow, aggregate-specific repository interface looks like with DI registration.

    Intermediate Theory Enterprise Patterns Β· πŸ”— 5 follow-ups
  2. Your team is starting a new .NET 10 service on EF Core 10 and is split on whether to wrap DbContext in repositories. How do you decide? Cover testability (mocks, the in-memory provider, Testcontainers), aggregate boundaries, leaking IQueryable, ExecuteUpdate/ExecuteDelete, and the situations where your answer changes.

    Architecture decision on wrapping EF Core in repositories: testing with mocks vs EF in-memory/SQLite vs Testcontainers SQL Server, aggregate repositories for the write side vs direct DbContext projections for reads, leaky IQueryable, EF Core 10 ExecuteUpdate/ExecuteDelete (non-expression setter lambda) bypassing the change tracker, multiple persistence stores, team skill and when the decision flips, recorded as an ADR.

    Senior Architecture Enterprise Patterns Β· πŸ”— 5 follow-ups Β· πŸ›  1 real-world
  3. What is the Unit of Work pattern? Explain how EF Core's DbContext already implements it with the change tracker and SaveChanges, when you need an explicit transaction (BeginTransactionAsync, execution strategies with retries), how ExecuteUpdate/ExecuteDelete fit in, and why all repositories in a request should share one DbContext.

    Unit of Work in .NET: tracking changes and committing them as one transaction, EF Core's change tracker and SaveChangesAsync as the built-in UoW (implicit transaction, identity map), explicit transactions with BeginTransactionAsync for multiple SaveChanges or ExecuteUpdate/ExecuteDelete/raw SQL, wrapping them in CreateExecutionStrategy().ExecuteAsync when EnableRetryOnFailure is on, TransactionScope caveats, and sharing one scoped DbContext across repositories.

    Intermediate Theory Enterprise Patterns Β· πŸ”— 2 follow-ups
  4. What is the difference between a service layer, an application service and a domain service? Explain what goes where in a DDD-style .NET application, how a fat service layer leads to an anaemic domain model, and how you keep business rules out of controllers and handlers.

    Service layer (Fowler) vs application service vs domain service (Evans/DDD): responsibilities (orchestration, transactions, authorisation and mapping vs stateless domain logic spanning aggregates), what belongs in entities, how 'god' service layers create an anaemic domain model, thin controllers/minimal API endpoints, and a funds-transfer example in .NET 10.

    Intermediate Theory Enterprise Patterns Β· πŸ”— 4 follow-ups
  5. What is a Data Transfer Object (DTO)? Explain where the pattern comes from, why you shouldn't return or bind EF Core entities directly in an ASP.NET Core API (over-posting, leaking fields, versioning, serialisation cycles), why C# records make good DTOs, and where DTOs are and aren't needed.

    DTO pattern: Fowler's origin (batching data across a process boundary), a data-only contract with no behaviour, why exposing EF Core entities in APIs is risky (over-posting/mass assignment, leaking sensitive fields under the Privacy Act, schema changes breaking clients, JSON object cycles), separate request and response DTOs, records as immutable DTOs, and when not to add DTOs (inside one layer).

    Junior Theory Enterprise Patterns Β· πŸ”— 3 follow-ups
  6. How should you map between EF Core entities and DTOs in .NET 10? Compare hand-written mapping, AutoMapper and Mapperly (a source generator), including their current licences, run-time cost and failure modes, and explain why projecting with Select (or ProjectTo) in the query often beats mapping entities after loading them.

    Mapper pattern in .NET 10: hand-written mapping (extension methods, constructors), AutoMapper (reflection/expression-compiled, ProjectTo, AssertConfigurationIsValid; dual RPL-1.5/commercial from v15, July 2025; free Community edition under US$5M revenue; 14.x last MIT with an unpatched advisory), Mapperly (Apache 2.0 source generator, build-time diagnostics, IQueryable projections), mapping after loading vs Select projection in EF Core (over-fetching, tracking, lazy-loading N+1), and testing mappings.

    Mid-Level Theory Enterprise Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  7. What is CQRS? Explain separating commands and queries into different models, the levels from separate handlers on one database to separate read stores updated by events, how it relates to CQS and to MediatR, how you handle eventual consistency in the UI, and when CQRS is overkill.

    CQRS (Command Query Responsibility Segregation): CQS (Meyer) vs CQRS (Young), separate write model (aggregates, invariants) and read model (projections/DTOs), levels from handlers on one database to a synchronous denormalised table to a separate read store fed by events, eventual consistency and read-your-writes in the UI, relationship to MediatR and event sourcing, and when CQRS is overkill.

    Mid-Level Theory Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  8. What is the transactional outbox pattern? Explain the dual-write problem when an order is saved to SQL Server and an event published to Azure Service Bus, how to write the outbox row in the same EF Core transaction, how a relay publishes and marks messages, why delivery is at-least-once, and what the pattern costs to operate.

    Transactional outbox: the dual-write problem (DB commit and broker publish can't be atomic; distributed transactions aren't an option with Azure SQL and Service Bus), writing an OutboxMessages row in the same EF Core SaveChanges/transaction, a relay BackgroundService polling with UPDLOCK/READPAST, publishing with MessageId = outbox id, marking ProcessedAt, at-least-once delivery and consumer idempotency, ordering, CDC as an alternative, library options (MassTransit v9 commercial, NServiceBus, Wolverine, CAP), and operational costs.

    Senior Theory Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  9. Implement an idempotent consumer (the inbox pattern) for Azure Service Bus messages in .NET 10: a dedup table with a unique key on message id and consumer, recording the message and applying the business change in one EF Core transaction, handling two copies of the same message arriving concurrently, and cleaning up old rows.

    Inbox / idempotent consumer in .NET 10: why at-least-once delivery (outbox resends, peek-lock redelivery, lock expiry) causes duplicates, an InboxMessages table with a composite primary key (MessageId, Consumer), inserting the inbox row first and applying the business change in the same EF Core transaction inside an execution strategy, treating SQL errors 2627/2601 as 'already processed', how the key lock serialises concurrent duplicates, completing vs abandoning Service Bus messages, retention-based cleanup with ExecuteDeleteAsync, natural idempotency as an alternative, and tests.

    Senior Coding Enterprise Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  10. Design a saga for an order-payment flow across orders, stock and payment services. Compare orchestration and choreography, explain compensating actions and why they aren't rollbacks, how a MassTransit state machine (or a hand-rolled orchestrator) persists saga state, and how you handle timeouts, duplicates and late replies.

    Saga pattern for a distributed order-payment flow: why there's no distributed transaction, orchestration (central state machine) vs choreography (services react to events), compensating actions as semantic undo (release stock, refund) rather than rollback, pivot transactions, MassTransit state machine with EF Core saga repository and optimistic concurrency (v9 commercial, v8 Apache 2.0), scheduled timeouts, idempotent steps, late replies after cancellation, observability, and alternatives (NServiceBus, Wolverine, Durable Functions).

    Senior Architecture Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  11. Explain the Retry pattern for transient faults in .NET 10: exponential backoff with jitter, which failures to retry and which never to retry, why retries need idempotency, how retry storms and retry amplification across layers happen, and how Polly v8 and Microsoft.Extensions.Http.Resilience implement it.

    Retry pattern: transient vs permanent faults (5xx, 408, 429 with Retry-After, timeouts vs 400/401/404/409), exponential backoff with jitter (Polly's decorrelated jitter), retrying only idempotent operations (DisableForUnsafeHttpMethods, idempotency keys), retry storms and multiplicative amplification across layers, retry budgets, Polly v8 ResiliencePipeline and RetryStrategyOptions, HttpRetryStrategyOptions defaults in AddStandardResilienceHandler, EF Core EnableRetryOnFailure, and telemetry.

    Mid-Level Theory Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  12. How does the circuit breaker pattern work? Explain the closed, open and half-open states, failure-ratio thresholds, minimum throughput, sampling and break duration, why it sits inside the retry and outside the per-attempt timeout, what AddStandardResilienceHandler configures by default, and how you choose a fallback.

    Circuit breaker pattern: closed/open/half-open state machine, Polly v8 CircuitBreakerStrategyOptions (FailureRatio 0.1, MinimumThroughput 100, SamplingDuration 30 s, BreakDuration 5 s, ShouldHandle, OnOpened/OnHalfOpened), BrokenCircuitException, ordering in AddStandardResilienceHandler (rate limiter, total timeout, retry, breaker, attempt timeout) and its validation rules, per-instance vs per-authority breakers (SelectPipelineByAuthority), low-traffic pitfalls, fallbacks and monitoring.

    Mid-Level Theory Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  13. What is the Bulkhead pattern? Explain how you isolate dependencies in a .NET 10 service with concurrency limiters, separate named HttpClients and pipelines, connection limits, and separate queues or consumers, how a bulkhead differs from rate limiting, and how you size the limits.

    Bulkhead pattern: isolating failures so one slow dependency can't consume shared resources (threads, sockets, DB connections, memory), outbound bulkheads with Polly v8 concurrency limiters (Polly.RateLimiting, RateLimiterRejectedException) and the standard resilience handler's limiter (1,000 permits, queue 0), separate named HttpClients and MaxConnectionsPerServer, inbound bulkheads with ASP.NET Core AddRateLimiter concurrency policies, separate queues/consumers and MaxConcurrentCalls, bulkhead vs rate limiting, sizing with Little's Law, and rejection handling.

    Senior Theory Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  14. A third-party shipping-rates API starts taking 30 seconds instead of 200 ms. Within minutes your checkout API is timing out for every user, including requests that never call that API. How do you diagnose the cascade, and how do you fix it with timeouts, retry, a circuit breaker, a bulkhead and a fallback?

    Real-world cascading failure: diagnosing with Application Insights dependency telemetry, dotnet-counters (thread pool, SqlClient pool, HTTP connections) and dotnet-dump; root causes (HttpClient 100 s default timeout, retries multiplying load, DB connections held across the external call, health checks including the dependency); mitigation with a feature flag; the real fix with attempt and total timeouts, a single jittered retry, a tuned circuit breaker, a concurrency-limit bulkhead, a flat-rate fallback, moving the call out of the transaction, and chaos testing.

    Senior RealWorldScenario Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  15. Orders are saved in SQL Server, but finance reports that some OrderPlaced messages on Azure Service Bus never arrive, and others are processed twice, charging customers twice. How do you find the causes, and how do you fix them with the outbox and inbox patterns without losing or duplicating anything during the rollout?

    Real-world messaging incident: finding lost events (publish after SaveChanges, fire-and-forget Task.Run, swallowed ServiceBusException) and duplicates (publisher retries with a new MessageId each time, peek-lock redelivery after lock expiry) with reconciliation queries, Application Insights correlation and Service Bus metrics; fixing with domain events written to an OutboxMessages table by a SaveChanges interceptor, a relay with UPDLOCK/READPAST and stable MessageId, duplicate detection, an InboxMessages table keyed on (MessageId, Consumer); rollout order (inbox first), backfill and refunds, and ongoing reconciliation.

    Senior RealWorldScenario Enterprise Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  16. You're setting the architecture for a new .NET 10 service. How do you decide which enterprise patterns (repository, unit of work, CQRS, mediator, domain services, outbox, sagas, resilience patterns) to use? Contrast a CRUD-heavy admin service with a complex domain such as insurance claims, explain how you avoid pattern overuse, and how you record and revisit those decisions.

    Staff-level pattern selection: starting from forces (domain complexity, invariants, consistency, integration, scale, team) rather than a template, a minimal baseline every service gets (DbContext, DTOs, validation, HttpClient resilience, observability), a CRUD admin service (vertical slices, DbContext in handlers, no repositories/CQRS/mediator) vs an insurance-claims domain (aggregates, repositories, domain services, light CQRS, outbox/inbox, saga for long-running claims), triggers for adding patterns, cost of each pattern, ADRs with reversal conditions, architecture fitness functions (NetArchTest), and periodic review.

    Staff / Architect Architecture Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me