I am getting below exception. Actually I am request multiple concurrent calls from UI using promise.All method it’s throwing exception I added my backedn code please check and let me know where is the problem
using Application.Abstractions.IRepositories;
using Codifi.Common.Core.Data;
using Codifi.Common.Core.Logging;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using System;
namespace DataAccess
{
public class MongoContext : IMongoContext
{
private IMongoDatabase Database { get; set; }
public IClientSessionHandle session { get; set; }
public MongoClient MongoClient { get; set; }
private readonly List<Func<IClientSessionHandle, Task>> commands;
public MongoContext(IConfiguration configuration)
{
// Every command will be stored and it'll be processed at SaveChanges
commands = new List<Func<IClientSessionHandle, Task>>();
}
public async Task<int> SaveChanges()
{
ConfigureMongo();
int count = 0;
using (session = await MongoClient.StartSessionAsync())
{
//Added majourity concern to check in every replicaset
var transactionOptions = new TransactionOptions(
writeConcern: WriteConcern.WMajority);
session.StartTransaction(transactionOptions);
try
{
// Pass Session to Commands: When executing the commands, pass the session to each command:
foreach (var command in commands)
{
await command(session);
}
//await Task.WhenAll(commandTasks); // We cannot run commands in parallel since we do not have a sharded cluster
await session.CommitTransactionAsync();
count = commands.Count;
commands.Clear();
}
catch (Exception ex)
{
// If an exception occurs, rollback the transaction
await session.AbortTransactionAsync();
ExceptionHelper.HandleException(ex);
throw; // Rethrow the exception for handling higher up the call stack
}
finally
{
commands.Clear(); // Ensure clearing happens in all cases
}
}
return count;
}
private void ConfigureMongo()
{
if (MongoClient != null)
{
return;
}
// Configure mongo (You can inject the config, just to simplify)
MongoClient = new MongoClient(DbHelper.GetMongoDbConnectionString());
Database = MongoClient.GetDatabase(DbHelper.GetMongoDbConnection.DatabaseName);
}
public IMongoCollection<T> GetCollection<T>(string name)
{
ConfigureMongo();
return Database.GetCollection<T>(name);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void AddCommand(Func<IClientSessionHandle, Task> func)
{
commands.Add(func);
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed && disposing)
{
session?.Dispose();
}
this.disposed = true;
}
}
}