Created
May 6, 2020 08:35
-
-
Save oguzhaneren/1a915fcd3056f09035729912422db480 to your computer and use it in GitHub Desktop.
SingletonInitializerFactory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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