using CommunityToolkit.Mvvm.Messaging; using Microsoft.Extensions.DependencyInjection; namespace Toolkit.Foundation; public class ComponentFactory(IServiceProvider provider, IProxyServiceCollection proxy, IComponentScopeCollection scopes) : IComponentFactory { public IComponentHost? Create(string key, Action>? configurationDelegate = null, Action? componentDelegate = null, Action? servicesDelegate = null) where TComponent : IComponent where TConfiguration : class, new() { if (provider.GetRequiredService() is TComponent component) { IComponentBuilder builder = component.Configure(configurationDelegate, componentDelegate); builder.AddServices(services => { services.AddTransient(_ => provider.GetRequiredService>()); services.AddTransient(_ => provider.GetRequiredService()); services.AddTransient(_ => provider.GetRequiredService>()); services.AddTransient(_ => provider.GetRequiredService>()); services.AddScoped(_ => provider.GetRequiredService()); services.AddScoped(_ => provider.GetRequiredService()); services.AddScoped(_ => provider.GetRequiredService()); services.AddTransient(_ => provider.GetRequiredService()); services.AddRange(proxy.Services); services.AddSingleton(new Scoped(key)); if (servicesDelegate is not null) { servicesDelegate(services); } }); IComponentHost host = builder.Build(); scopes.Add(new ComponentScopeDescriptor(key, host.Services.GetRequiredService())); return host; } return default; } }