MemoryCache
namespace RealWebDevelopers;
public class Provider
{
private readonly IMemoryCache memoryCache;
private readonly MemoryCacheEntryOptions memoryCacheEntryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60); // Cache for 1 hour
}
public Provider(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
}
public IEnumberable<Product> GetProducts()
{
var cacheKey = "product";
if (!this.memoryCache.TryGetValue(cacheKey, out List<Product> productCache))
{
try
{
// Fetch the data from source i.e. Database query
var products = this.session.Query<Product>();
this.memoryCache.Set(cacheKey, products, this.memoryCacheEntryOptions);
return products;
}
catch
{
// Whatever
}
}
return productCache;
}
}
Full article
Service collection Jaeger
namespace RealWebDevelopers;
using Microsoft.Extensions.Options;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
public class Program
{
public static void Main(string[] args)
{
// boiler plate web application
builder.Services.AddOpenTelemetry()
.WithTracing(configure =>
{
configure.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(builder.Environment.ApplicationName))
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddSource(builder.Environment.ApplicationName)
.AddOtlpExporter(config => { config.Endpoint = new Uri("http://localhost:4317"); });
});
// etc.
}
}
Full article
Case-insensitive Dictionary access in C#
namespace RealWebDevelopers;
using System;
using System.Collections.Generic;
public static class Program
{
private static readonly Dictionary cache = new(StringComparer.OrdinalIgnoreCase)
{
{
"dog", "woof"
},
{
"cat", "meow"
};
};
public static void Main(string[] args)
{
Console.Write(cache.GetValueOrDefault("dog"));
Console.Write(cache.GetValueOrDefault("Dog"));
}
}
Full article
Service Collection RabbitMQ extension
namespace RealWebDevelopers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
public static class Extensions
{
public static void AddRabbitMq(this ServiceCollection services)
{
services.AddSingleton(implementationFactory =>
{
return new ConnectionFactory
{
HostName = implementationFactory.GetRequiredService>().Value.Host,
}.CreateConnectionAsync().Result;
});
return services;
}
}
Full article