| | | 1 | | using Elsa.Common.Multitenancy; |
| | | 2 | | using Elsa.Extensions; |
| | | 3 | | using JetBrains.Annotations; |
| | | 4 | | using Microsoft.EntityFrameworkCore; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Persistence.EFCore; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// A factory class that wraps and extends the functionality of an existing <see cref="IDbContextFactory{TDbContext}"/> |
| | | 10 | | /// to provide multi-tenancy support. This ensures that the created DbContext instances are aware of the current tenant |
| | | 11 | | /// </summary> |
| | | 12 | | [UsedImplicitly] |
| | 1653 | 13 | | public class TenantAwareDbContextFactory<TDbContext>( |
| | 1653 | 14 | | IDbContextFactory<TDbContext> decoratedFactory, |
| | 1653 | 15 | | ITenantAccessor tenantAccessor) : IDbContextFactory<TDbContext> |
| | | 16 | | where TDbContext : DbContext |
| | | 17 | | { |
| | | 18 | | public TDbContext CreateDbContext() |
| | | 19 | | { |
| | 0 | 20 | | var context = decoratedFactory.CreateDbContext(); |
| | 0 | 21 | | SetTenantId(context); |
| | 0 | 22 | | return context; |
| | | 23 | | } |
| | | 24 | | |
| | | 25 | | public async Task<TDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default) |
| | | 26 | | { |
| | 12663 | 27 | | var context = await decoratedFactory.CreateDbContextAsync(cancellationToken); |
| | 12663 | 28 | | SetTenantId(context); |
| | 12663 | 29 | | return context; |
| | 12663 | 30 | | } |
| | | 31 | | |
| | | 32 | | private void SetTenantId(TDbContext context) |
| | | 33 | | { |
| | 12663 | 34 | | if (context is ElsaDbContextBase elsaContext) |
| | 12663 | 35 | | elsaContext.TenantId = tenantAccessor.Tenant?.Id.NullIfEmpty(); |
| | 12663 | 36 | | } |
| | | 37 | | } |