⚡ AutoSnippets PRO PL

C#: Production Code Snippets

C# / .NET snippets: EF Core, middleware, background services, caching.

Python JavaScript TypeScript Java C# C++ Go PHP Rust SQL

On this page:

21. C#: Generic Repository (EF Core)

C#

A universal data-access layer with async support.

public class Repository where T : class {
    private readonly DbContext _context;
    private readonly DbSet _dbSet;

    public Repository(DbContext context) {
        _context = context;
        _dbSet = context.Set();
    }

    public async Task GetByIdAsync(int id) => await _dbSet.FindAsync(id);
}

When to use

Useful when many entities in the database require the same basic CRUD operations.

Common pitfalls

An overly generic repository makes it harder to add specific Include() queries or complex filters — sometimes it's better to split off inheriting repositories.

22. C#: Global Exception Middleware

C#

Catching errors in ASP.NET Core and returning JSON.

public class ExceptionMiddleware {
    private readonly RequestDelegate _next;
    public ExceptionMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(HttpContext context) {
        try { await _next(context); }
        catch (Exception ex) {
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { error = ex.Message });
        }
    }
}

When to use

Worth adding to every ASP.NET Core app to get a consistent API error format instead of .NET's default error pages.

Common pitfalls

Returning ex.Message directly to the client can leak implementation details — in production, log the full error and return a generic message to the client.

23. C#: Background Hosted Service

C#

A long-running background process that performs recurring system tasks.

public class TimedWorker : BackgroundService {
    protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
        while (!stoppingToken.IsCancellationRequested) {
            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
        }
    }
}

When to use

Ideal for recurring background tasks across the whole application, e.g. cache cleanup, sending reports, polling an external API.

Common pitfalls

An unhandled exception inside ExecuteAsync can silently stop the whole background service — add error handling inside the loop.

24. C#: Options Configuration Injection

C#

Configuring strongly typed application settings in .NET.

public class SmtpSettings {
    public string Host { get; set; } = string.Empty;
    public int Port { get; set; }
}

// Rejestracja: builder.Services.Configure(builder.Configuration.GetSection("Smtp"));

When to use

Use it instead of reading appsettings.json manually — it gives strong typing and easier configuration testing.

Common pitfalls

Changing a value in appsettings.json at runtime won't update automatically unless you use IOptionsMonitor instead of IOptions.

25. C#: Caching with Stampede Protection

C#

Fetching data with a locking mechanism that prevents overload.

using Microsoft.Extensions.Caching.Memory;

public class CachedService {
    private readonly IMemoryCache _cache;
    public async Task GetDataAsync(string key) {
        return await _cache.GetOrCreateAsync(key, async entry => {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
            return await FetchFromDatabaseAsync();
        });
    }
    private Task FetchFromDatabaseAsync() => Task.FromResult("Dane");
}

When to use

Useful for expensive operations (database queries, external API calls) requested by many users at once.

Common pitfalls

Without a lock (as in GetOrCreateAsync), cache expiry can trigger dozens of concurrent requests to the data source at the same moment — the so-called cache stampede.