Skip to content

Instantly share code, notes, and snippets.

View gusarov's full-sized avatar

Dmitry Gusarov gusarov

View GitHub Profile
@gusarov
gusarov / program.cs
Last active December 23, 2024 20:25
DI Container service graph branches
using Microsoft.Extensions.DependencyInjection;
var serviceCollection = new ServiceCollection();
serviceCollection.AddScoped<JsonConfigUpdater>();
serviceCollection.AddScoped<JsonConfigUpdaterSettigns>();
serviceCollection.AddSingleton<ConfigUpdaterManager>();
var provider = serviceCollection.BuildServiceProvider();
@gusarov
gusarov / resolveKeyed.cs
Last active December 23, 2024 20:22
Resolve keyed service by name with convenient generic interface with double arity match
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
var appBuidler = Host.CreateApplicationBuilder();
appBuidler.Services.AddKeyedSingleton<IService, Serivce1>("abc");
appBuidler.Services.AddKeyedSingleton<IService, Serivce2>("def");
appBuidler.Services.AddSingleton<Test>();
@gusarov
gusarov / program.cs
Created December 23, 2024 20:46
Prevent duplicated service registration
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
namespace CompanyName;
internal class Program
{
private static void Main(string[] args)
@gusarov
gusarov / program.cs
Created December 23, 2024 21:07
Prevent duplicated service registration before build using decorator
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
namespace CompanyName;
internal class Program
{
private static void Main(string[] args)
public class CustomLog : IDisposable, IAsyncDisposable
{
StreamWriter _log;
Channel<string> _channel = Channel.CreateUnbounded<string>();
Task _writer;
CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
Timer _flusher;
SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
public CustomLog(string logName)