| | | 1 | | using Elsa.Workflows; |
| | | 2 | | using Elsa.Workflows.Models; |
| | | 3 | | using Microsoft.Extensions.DependencyInjection; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection.Extensions; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Extensions; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Adds output converter registrations to a service collection. |
| | | 10 | | /// </summary> |
| | | 11 | | public static class OutputConverterServiceCollectionExtensions |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Registers a discoverable output converter using its stable Converter ID as the keyed-service key. |
| | | 15 | | /// </summary> |
| | | 16 | | public static IServiceCollection AddOutputConverter<TConverter>( |
| | | 17 | | this IServiceCollection services, |
| | | 18 | | OutputConverterDescriptor descriptor, |
| | | 19 | | ServiceLifetime serviceLifetime = ServiceLifetime.Scoped) |
| | | 20 | | where TConverter : class, IOutputConverter |
| | | 21 | | { |
| | 8 | 22 | | ArgumentNullException.ThrowIfNull(services); |
| | 8 | 23 | | ArgumentNullException.ThrowIfNull(descriptor); |
| | | 24 | | |
| | 8 | 25 | | OutputConverterRegistry.ValidateDescriptor(descriptor); |
| | 8 | 26 | | ValidateUniqueId(services, descriptor.Id); |
| | | 27 | | |
| | 8 | 28 | | var registration = new OutputConverterRegistration(descriptor, descriptor.Id, serviceLifetime); |
| | 8 | 29 | | services.AddSingleton(registration); |
| | 8 | 30 | | services.Add(ServiceDescriptor.DescribeKeyed( |
| | 8 | 31 | | typeof(IOutputConverter), |
| | 8 | 32 | | descriptor.Id, |
| | 8 | 33 | | typeof(TConverter), |
| | 8 | 34 | | serviceLifetime)); |
| | 8 | 35 | | services.TryAddSingleton<IOutputConverterRegistry, OutputConverterRegistry>(); |
| | 8 | 36 | | return services; |
| | | 37 | | } |
| | | 38 | | |
| | | 39 | | private static void ValidateUniqueId(IServiceCollection services, string id) |
| | | 40 | | { |
| | 8 | 41 | | if (string.IsNullOrWhiteSpace(id)) |
| | 0 | 42 | | throw new ArgumentException("Output converter IDs cannot be empty.", nameof(id)); |
| | | 43 | | |
| | 8 | 44 | | var existingRegistration = services |
| | 3012 | 45 | | .Where(x => x.ServiceType == typeof(OutputConverterRegistration)) |
| | 0 | 46 | | .Select(x => x.ImplementationInstance) |
| | 8 | 47 | | .OfType<OutputConverterRegistration>() |
| | 8 | 48 | | .FirstOrDefault(x => string.Equals(x.Descriptor.Id, id, StringComparison.OrdinalIgnoreCase)); |
| | | 49 | | |
| | 8 | 50 | | if (existingRegistration != null) |
| | 0 | 51 | | throw new InvalidOperationException($"Output converter ID '{id}' is already registered or differs from '{exi |
| | 8 | 52 | | } |
| | | 53 | | } |