Skip to content

Instantly share code, notes, and snippets.

@oguzhaneren
Created May 6, 2020 08:35
Show Gist options
  • Save oguzhaneren/1a915fcd3056f09035729912422db480 to your computer and use it in GitHub Desktop.
Save oguzhaneren/1a915fcd3056f09035729912422db480 to your computer and use it in GitHub Desktop.
SingletonInitializerFactory
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace XXX
{
public static class SingletonExtensions
{
public static IServiceCollection InitEarly<T>(this IServiceCollection serviceCollection)
{
serviceCollection.TryAddSingleton<SingletonInitializer>();
serviceCollection.AddSingleton<ISingletonInitializerFactory>(sp => new GenericSingletonInitializerFactory<T>(sp.GetRequiredService<T>));
return serviceCollection;
}
}
public interface ISingletonInitializerFactory
{
void Init();
}
class GenericSingletonInitializerFactory<T> : ISingletonInitializerFactory
{
private readonly Func<T> _factory;
public GenericSingletonInitializerFactory(Func<T> factory)
{
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
}
public void Init()
{
_factory();
}
}
public class SingletonInitializer
{
private readonly IEnumerable<ISingletonInitializerFactory> _factories;
public SingletonInitializer(IEnumerable<ISingletonInitializerFactory> factories)
{
_factories = factories;
}
public void Init()
{
foreach (var factory in _factories)
{
factory.Init();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment