After several years building APIs for ERP, eCommerce and fintech systems, a handful of habits keep my ASP.NET Core projects easy to change and safe to run in production. None of them are new, but applied consistently they make a big difference.
Controllers should handle HTTP concerns only: routing, model binding and status codes. Business logic belongs in services, which makes it testable and reusable across endpoints and background jobs.
[ApiController]
[Route("api/settlements")]
public class SettlementsController : ControllerBase
{
private readonly ISettlementService _settlements;
public SettlementsController(ISettlementService settlements) => _settlements = settlements;
[HttpGet("{merchantId:int}")]
public async Task<IActionResult> Get(int merchantId, [FromQuery] DateRange range)
{
var result = await _settlements.GetForMerchantAsync(merchantId, range);
return result is null ? NotFound() : Ok(result);
}
}
Register dependencies with the right lifetime. Anything tied to a request, such as a database connection or context, should be Scoped. Depending on interfaces keeps components replaceable and makes unit testing straightforward.
builder.Services.AddScoped<ISettlementService, SettlementService>();
builder.Services.AddScoped<ISettlementRepository, SettlementRepository>();
builder.Services.AddSingleton<IClock, SystemClock>(); // stateless, safe to share
A common bug: injecting a scoped service into a singleton. The scoped object then lives forever and shares state across requests. ASP.NET Core catches this in Development, so keep scope validation on.
Whether you use EF Core or Dapper, keep queries out of your business logic. A repository or query layer gives you one place to optimise SQL, add caching, or switch an expensive query to Dapper without touching the rest of the code.
public class SettlementRepository : ISettlementRepository
{
private readonly IDbConnection _db;
public SettlementRepository(IDbConnection db) => _db = db;
public Task<IEnumerable<Settlement>> GetAsync(int merchantId, DateTime from, DateTime to) =>
_db.QueryAsync<Settlement>(
"SELECT Id, Amount, Status, SettledAt FROM dbo.Settlements " +
"WHERE MerchantId = @merchantId AND SettledAt >= @from AND SettledAt < @to",
new { merchantId, from, to });
}
Define authorization policies centrally and apply them with attributes, rather than scattering role checks through the code. Default to denying access and grant only what each role needs.
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build(); // deny anonymous by default
options.AddPolicy("CanApproveSettlements",
p => p.RequireRole("FinanceManager", "Admin"));
});
[Authorize(Policy = "CanApproveSettlements")]
[HttpPost("{id:int}/approve")]
public Task<IActionResult> Approve(int id) => ...
Reject bad input before it reaches your services. With [ApiController], invalid models automatically return a 400 with a standard ProblemDetails body, which makes your API predictable for frontend and mobile teams.
public record CreatePayoutRequest(
[Required] string MerchantCode,
[Range(1, 10_000_000)] decimal Amount,
[Required, StringLength(34)] string Iban);
builder.Services.AddProblemDetails(); // consistent error shape everywhere
Structured logs with correlation IDs turn production incidents from guesswork into a quick search. Log properties, not concatenated strings, so you can filter by merchant, payment or request.
// ❌ Hard to search
_logger.LogInformation("Payout " + payoutId + " failed for merchant " + merchantId);
// ✅ Every value becomes a searchable field
_logger.LogWarning("Payout {PayoutId} failed for merchant {MerchantId}: {Reason}",
payoutId, merchantId, reason);
Pair this with global exception handling, so every unexpected error is logged once with its request ID and the client gets a clean 500 instead of a stack trace.
Clean architecture is not about layers for their own sake; it is about making the next change cheap and the system reliable under load.