static Task SendToInstance <T>(SagaQueryConsumeContext <TSaga, T> context, ISagaPolicy <TSaga, T> policy, TSaga instance, IPipe <SagaConsumeContext <TSaga, T> > next, ISession session) where T : class { try { var sagaConsumeContext = new NHibernateSagaConsumeContext <TSaga, T>(session, context, instance); sagaConsumeContext.LogUsed(); return(policy.Existing(sagaConsumeContext, next)); } catch (SagaException) { throw; } catch (Exception ex) { throw new SagaException(ex.Message, typeof(TSaga), typeof(T), instance.CorrelationId, ex); } }
async Task ISagaRepository <TSaga> .Send <T>(ConsumeContext <T> context, ISagaPolicy <TSaga, T> policy, IPipe <SagaConsumeContext <TSaga, T> > next) { if (!context.CorrelationId.HasValue) { throw new SagaException("The CorrelationId was not specified", typeof(TSaga), typeof(T)); } var sagaId = context.CorrelationId.Value; using (var session = _sessionFactory.OpenSession()) using (var transaction = session.BeginTransaction()) { var inserted = false; if (policy.PreInsertInstance(context, out var instance)) { inserted = await PreInsertSagaInstance(context, session, instance).ConfigureAwait(false); } try { if (instance == null) { instance = await session.GetAsync <TSaga>(sagaId, LockMode.Upgrade).ConfigureAwait(false); } if (instance == null) { var missingSagaPipe = new MissingPipe <T>(session, next); await policy.Missing(context, missingSagaPipe).ConfigureAwait(false); } else { var sagaConsumeContext = new NHibernateSagaConsumeContext <TSaga, T>(session, context, instance); sagaConsumeContext.LogUsed(); await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false); if (inserted && !sagaConsumeContext.IsCompleted) { await session.UpdateAsync(instance).ConfigureAwait(false); } } if (transaction.IsActive) { await transaction.CommitAsync().ConfigureAwait(false); } } catch (Exception ex) { context.LogFault(this, ex, instance?.CorrelationId); if (transaction.IsActive) { await transaction.RollbackAsync().ConfigureAwait(false); } throw; } } }