© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
92 replies
Aljo_M

❔ MongoDb transactions in Asp.net core web api

Hello, i need some advice on what is the best thing to do. I am building asp.net core Web API with MongoDb identity. The logic goes like this controller > service > dbManagers.

I want to implement transactions so i can revert db operation if anything goes wrong. Now i dont want to repeat myself and add
using (var session = await _dbClient.StartSessionAsync())
using (var session = await _dbClient.StartSessionAsync())
in every method, instead i created a middleware:

public class DbTransactionMiddleware
{
  private readonly RequestDelegate _next;
  private readonly DbClient _dbClient;

  public DbTransactionMiddleware(RequestDelegate next, DbClient dbClient)
  {
    _next = next;
    _dbClient = dbClient;
  }

  public async Task InvokeAsync(HttpContext context)
  {
    using (var session = await _dbClient.StartSessionAsync())
    {
      session.StartTransaction();

      try
      {
        await _next(context);
        await session.CommitTransactionAsync();
      }
      catch (Exception ex)
      {
        await session.AbortTransactionAsync();
        throw;
      }
     }
    }
  }
public class DbTransactionMiddleware
{
  private readonly RequestDelegate _next;
  private readonly DbClient _dbClient;

  public DbTransactionMiddleware(RequestDelegate next, DbClient dbClient)
  {
    _next = next;
    _dbClient = dbClient;
  }

  public async Task InvokeAsync(HttpContext context)
  {
    using (var session = await _dbClient.StartSessionAsync())
    {
      session.StartTransaction();

      try
      {
        await _next(context);
        await session.CommitTransactionAsync();
      }
      catch (Exception ex)
      {
        await session.AbortTransactionAsync();
        throw;
      }
     }
    }
  }


But how can i access session object in my service. And what would be the better way to do something like this. Like what is best practice?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

✅ ASP.Net Core Web API
C#CC# / help
6mo ago
ASP.NET CORE MVC VS ASP.NET CORE WEB API
C#CC# / help
17mo ago
✅ Testing in ASP.NET Core Web Api
C#CC# / help
9mo ago
✅ ASP.NET Core Web Api + SignalR
C#CC# / help
2y ago