using System.Threading.Channels; using Elsa.Expressions; using Elsa.Mediator.Extensions; using Elsa.Runtime.HostedServices; using Elsa.Runtime.Implementations; using Elsa.Runtime.Interpreters; using Elsa.Runtime.Models; using Elsa.Runtime.Options; using Elsa.Runtime.Services; using Elsa.Runtime.Stimuli.Handlers; using Elsa.Runtime.WorkflowProviders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace Elsa.Runtime.Extensions; public static class ServiceCollectionExtensions { public static IServiceCollection AddElsaRuntime(this IServiceCollection services) { services.AddOptions(); return services // Core. .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton(sp => sp.GetRequiredService>().Value.WorkflowInvokerFactory(sp)) .AddSingleton(sp => sp.GetRequiredService>().Value.WorkflowDispatcherFactory(sp)) // Stimulus handlers. .AddStimulusHandler() .AddStimulusHandler() // Instruction interpreters. .AddInstructionInterpreter() .AddInstructionInterpreter() // Workflow definition providers. .AddWorkflowDefinitionProvider() // Workflow engine. .AddSingleton() // Domain event handlers. .AddNotificationHandlersFrom(typeof(ServiceCollectionExtensions)) // Hosted Services. .AddHostedService() .AddHostedService() .AddHostedService() .AddHostedService() .AddHostedService() // Channels for dispatching workflows in-memory. .CreateChannel() .CreateChannel() ; } private static IServiceCollection CreateChannel(this IServiceCollection services) => services .AddSingleton(CreateChannel()) .AddSingleton(CreateChannelReader) .AddSingleton(CreateChannelWriter); private static Channel CreateChannel() => Channel.CreateUnbounded(new UnboundedChannelOptions()); private static ChannelReader CreateChannelReader(IServiceProvider serviceProvider) => serviceProvider.GetRequiredService>().Reader; private static ChannelWriter CreateChannelWriter(IServiceProvider serviceProvider) => serviceProvider.GetRequiredService>().Writer; public static IServiceCollection AddDefaultExpressionHandlers(this IServiceCollection services) => services .AddExpressionHandler() .AddExpressionHandler() .AddExpressionHandler() .AddExpressionHandler() .AddExpressionHandler() .AddExpressionHandler(); public static IServiceCollection AddWorkflowDefinitionProvider(this IServiceCollection services) where T : class, IWorkflowDefinitionProvider => services.AddSingleton(); public static IServiceCollection AddStimulusHandler(this IServiceCollection services) where T : class, IStimulusHandler => services.AddSingleton(); public static IServiceCollection AddInstructionInterpreter(this IServiceCollection services) where T : class, IWorkflowInstructionInterpreter => services.AddSingleton(); public static IServiceCollection ConfigureWorkflowRuntime(this IServiceCollection services, Action configure) => services.Configure(configure); }