TurnerSoftware / MongoFramework

An "Entity Framework"-like interface for MongoDB
MIT License
392 stars 35 forks source link

DBContext / DBConnection life cycle #346

Closed joelsteventurner closed 1 year ago

joelsteventurner commented 1 year ago

I'm not sure I'm using the DBContext and Connection as intended.

When you dispose the DB Context it closes the DB Connection. This usage pattern would imply a new DB connection per DB Context. The DB Connection under the hood seems to be a handle to a MongoClient, which as I understand is supposed to be a long-lived object. "Store your MongoClient instance in a place that is globally accessible by your application." - https://www.mongodb.com/docs/manual/administration/connection-pool-overview/

EF DB Context are typically request bound for Web Applications, am I doing something wrong here.

My current work around is to override the Dispose method on the DBContext and not call the base one, and using the Singleton DB Connection for all DB Contexts.

Turnerj commented 1 year ago

So yes and no - like you've noticed, my MongoDbConnection wraps a MongoClient but MongoClient itself doesn't hold the connection pool, a static cluster registry within MongoDB's C# driver does. You can see it here in the driver's source code: https://github.com/mongodb/mongo-csharp-driver/blob/3d41388c9bfece7ae00daeadfe3afb07ba40808f/src/MongoDB.Driver/MongoClient.cs#L81

Back to the MongoDbConnection though, I probably could stop disposing it so aggressively though I think that's probably more a task when I land service collection extensions for MongoFramework.

Have you had a specific issue with DB contexts and connections or was this more a curiosity based on that doc from MongoDB's site?

joelsteventurner commented 1 year ago

Ok great, that makes sense, so I can treat the MongoDBConnection as transient. I have not experienced any issues my side.

Turnerj commented 1 year ago

Yeah, that's how I use it. Hopefully in the coming months I can get an update to ServiceCollection extensions making this more abstracted away so it is less of a concern.