using Elsa.Common.Entities; using Elsa.Features.Abstractions; using Elsa.Features.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace Elsa.EntityFrameworkCore.Common; /// /// Base class for features that require Entity Framework Core. /// /// The type of the database context. public abstract class PersistenceFeatureBase : FeatureBase where TDbContext : DbContext { /// protected PersistenceFeatureBase(IModule module) : base(module) { } /// /// Gets or sets a value indicating whether to use context pooling. /// public bool UseContextPooling { get; set; } /// /// Gets or sets a value indicating whether to run migrations. /// public bool RunMigrations { get; set; } = true; /// /// Gets or sets the lifetime of the . Defaults to . /// public ServiceLifetime DbContextFactoryLifetime { get; set; } = ServiceLifetime.Singleton; /// /// Gets or sets the callback used to configure the . /// public Action DbContextOptionsBuilder = (_, options) => options .UseSqlite("Data Source=elsa.sqlite.db;Cache=Shared;", sqlite => sqlite .MigrationsAssembly("Elsa.EntityFrameworkCore.Sqlite") .MigrationsHistoryTable(ElsaDbContextBase.MigrationsHistoryTable, ElsaDbContextBase.ElsaSchema)); /// public override void ConfigureHostedServices() { if (RunMigrations) Module.ConfigureHostedService>(-100); // Migrations need to run before other hosted services that depend on DB access. } /// public override void Apply() { if (UseContextPooling) Services.AddPooledDbContextFactory(DbContextOptionsBuilder); else Services.AddDbContextFactory(DbContextOptionsBuilder, DbContextFactoryLifetime); } /// /// Adds a store to the service collection. /// /// The type of the entity. /// The type of the store. protected void AddStore() where TEntity : class where TStore : class { Services .AddSingleton>() .AddSingleton() ; } /// /// Adds an entity store to the service collection. /// /// The type of the entity. /// The type of the store. protected void AddEntityStore() where TEntity : Entity where TStore : class { Services .AddSingleton>() .AddSingleton() ; } }