❔ 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())
in every method, instead i created a middleware:
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?31 Replies
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
so i should put
in all my service methods?
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
okay sorry i misunderstood
so, i should delete that middleware and register it as a scoped service, then inject it in lets say my UserService?
let me just give you example:
this is in my UserService.cs
how to implement it here?
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
i actually have dbClient and all dbManagers registered as singletons
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
i am a complete beginner, sorry
but okay UserService is scoped
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
what would you do?
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
why is UserService scoped?
okay, i can make it transient
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
i was asking what is better to do instead of that, in case that is not common practice?
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
i saw some example, and didnt want to use start transaction in all my methods
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
yes i understand that
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
yes ofcourse
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
yes okay
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
i get it
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
sure
okay thanks
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
so i created a scoped service and kept the middleware. in the middleware i run the scoped service to create transaction and then set the session object into context like this:
this is just to play around. what do you think about it?
Unknown User•15mo ago
Message Not Public
Sign In & Join Server To View
😂
okay thank you :)
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.