Introduction

In this article, we will see the Best practice to make your project cleaner in .NET Core.

Let's get started.

1. Project Structure and Layering

Use solution folders to organize these projects.

/MyCleanProject
  /MyCleanProject.Api         <-- ASP.NET Core Web API
  /MyCleanProject.Application <-- Business Logic, Services, DTOs
  /MyCleanProject.Domain      <-- Entities, Interfaces
  /MyCleanProject.Infrastructure <-- EF Core, Repositories, Data Access
  /MyCleanProject.Tests       <-- Unit Tests

2. Use Dependency Injection (DI)

Example in Startup.cs or Program.cs (for .NET 6+ minimal hosting):

services.AddScoped<IUserService, UserService>();

services.AddSingleton<IMySingletonService, MySingletonService>();

3. Configuration Management

4. Logging

5. Use EF Core with Best Practices

6. API Design (if using Web API)

7. Middleware and Pipeline

8. Async Programming

9. Testing

10. Security

Example Minimal Startup Setup in .NET 6+

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddScoped<IUserService, UserService>();

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddLogging();
// Build the app
var app = builder.Build();
// Configure middleware pipeline
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

Conclusion

Here we tried to cover Best practice to make your project cleaner in .NET Core.