Skip to content

Instantly share code, notes, and snippets.

@usausa
Created September 4, 2021 05:47
Show Gist options
  • Save usausa/a58aa0622d22adbd265e2815aef76b90 to your computer and use it in GitHub Desktop.
Save usausa/a58aa0622d22adbd265e2815aef76b90 to your computer and use it in GitHub Desktop.
namespace ComponentManagement
{
using System;
using Microsoft.Extensions.DependencyInjection;
public static class Program
{
public static void Main(string[] args)
{
var config = new ServiceCollection();
config.AddTransient<Data>();
config.AddComponent(c =>
{
// Component config ...
});
var provider = config.BuildServiceProvider();
var component = provider.GetService<Component>();
var data = component.Create<Data>();
}
}
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddComponent(this IServiceCollection services, Action<ComponentConfig> action)
{
var config = new ComponentConfig();
action(config);
return services.AddSingleton(p =>
{
config.Provider = p;
return new Component(config);
});
}
}
public sealed class ComponentConfig
{
public IServiceProvider Provider { get; set; }
// ...
}
public sealed class Component
{
private readonly IServiceProvider serviceProvider;
public Component(ComponentConfig config)
{
serviceProvider = config.Provider;
// ...
}
public T Create<T>() => serviceProvider.GetService<T>();
}
public class Data
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment