|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using PatternKit.Generators.Factories; |
| 4 | + |
| 5 | +namespace PatternKit.Examples.Generators; |
| 6 | + |
| 7 | +// NOTE: This is a minimal stub to ensure the examples and docfx metadata build without |
| 8 | +// depending on source generator output. The real implementation may be augmented |
| 9 | +// by the PatternKit.Generators FactoryClass source generator via partial types. |
| 10 | + |
| 11 | +public partial class OrchestratorStepFactory |
| 12 | +{ |
| 13 | + private readonly IServiceProvider _services; |
| 14 | + private readonly IReadOnlyDictionary<string, Type> _stepTypes; |
| 15 | + |
| 16 | + public OrchestratorStepFactory(IServiceProvider? services = null) |
| 17 | + { |
| 18 | + _services = services ?? throw new ArgumentNullException(nameof(services)); |
| 19 | + |
| 20 | + // These keys must match the [FactoryClassKey] attributes on the step types. |
| 21 | + _stepTypes = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase) |
| 22 | + { |
| 23 | + { "seed", typeof(SeedDataStep) }, |
| 24 | + { "warm-cache", typeof(WarmCacheStep) }, |
| 25 | + { "start-workers", typeof(StartWorkersStep) }, |
| 26 | + }; |
| 27 | + } |
| 28 | + |
| 29 | + // Use a different method name so we don't collide with the source-generated |
| 30 | + // OrchestratorStepFactory.Create method. |
| 31 | + public IOrchestratorStep CreateFromKey(string key) |
| 32 | + { |
| 33 | + if (key is null) throw new ArgumentNullException(nameof(key)); |
| 34 | + |
| 35 | + if (!_stepTypes.TryGetValue(key, out var type)) |
| 36 | + { |
| 37 | + throw new KeyNotFoundException($"Unknown orchestrator step key: '{key}'."); |
| 38 | + } |
| 39 | + |
| 40 | + // Resolve from the service provider if possible, otherwise fall back to Activator. |
| 41 | + var instance = _services.GetService(type) ?? Activator.CreateInstance(type); |
| 42 | + if (instance is not IOrchestratorStep step) |
| 43 | + { |
| 44 | + throw new InvalidOperationException($"Type '{type.FullName}' does not implement {nameof(IOrchestratorStep)}."); |
| 45 | + } |
| 46 | + |
| 47 | + return step; |
| 48 | + } |
| 49 | +} |
0 commit comments