Created
September 4, 2021 05:47
-
-
Save usausa/a58aa0622d22adbd265e2815aef76b90 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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