using Elsa.Caching; using Elsa.Caching.Features; using Elsa.EntityFrameworkCore.Modules.Management; using Elsa.Expressions.Contracts; using Elsa.Expressions.Services; using Elsa.Extensions; using Elsa.Features.Implementations; using Elsa.Workflows; using Elsa.Workflows.Serialization.Serializers; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using StackExchange.Redis; namespace Elsa.Caching.UnitTests; public static class CacheTestHost { public static ServiceProvider Create(string? databasePath = null, bool redis = false, string? prefix = null, Action? configure = null, Microsoft.EntityFrameworkCore.Diagnostics.DbCommandInterceptor? interceptor = null) { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(WellKnownTypeRegistry.CreateDefault()); services.AddSingleton(); if (databasePath != null) services.AddDbContextFactory(o => { o.UseSqlite($"Data Source={databasePath}"); if (interceptor != null) o.AddInterceptors(interceptor); }); if (redis) services.AddSingleton(_ => ConnectionMultiplexer.Connect( Environment.GetEnvironmentVariable("REDIS_TEST_CONNECTION") ?? "127.0.0.1:16379,abortConnect=false,connectTimeout=1000,syncTimeout=1000")); var module = new Module(services); module.UseCaching(cache => { cache.RegisterRedis(); if (databasePath != null) cache.ConsistencyStore = sp => ActivatorUtilities.CreateInstance(sp); if (redis) cache.UseRedis(o => { o.Database = 1; o.KeyPrefix = prefix ?? "workflow-tests:" + Guid.NewGuid().ToString("N") + ":"; }); configure?.Invoke(cache); }); module.Apply(); return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); } public static async Task EnsureCreatedAsync(IServiceProvider services) { using var scope = services.CreateScope(); await using var db = await scope.ServiceProvider.GetRequiredService>().CreateDbContextAsync(); await db.Database.EnsureCreatedAsync(); } }