MongoClient in ASP.NET Core: lifetime and shutdown ownership
The article explains how to register MongoClient as a singleton in ASP.NET Core and how request-scoped services should borrow it. It shows that disposing the client through the container does not close the driver's cluster, and that the selected driver version changes the answer. It is a useful reference for teams running MongoDB in web apps.
Key points
- Register MongoClient as a singleton in DI; do not create a new client per request.
- Read the connection string from configuration such as Mongo:ConnectionString and throw at startup if it is missing, rather than falling back silently to localhost.
- Let request-scoped services borrow the shared client and keep per-request state out of it.
- Disposing MongoClient through the container does not close the cluster; ClusterRegistry.UnregisterAndDisposeCluster should be used only once you have proven ownership.
- Getting a database or collection handle is not a connectivity check; run a real server operation to verify access.
- Verify the examples against driver 3.12.0 and the current connection documentation, since they were not executed.
The article asks how long an ASP.NET Core application should keep a MongoClient and who owns the resources behind it. A singleton registration covers client reuse, but it does not by itself settle shutdown, since the driver's cluster infrastructure can be shared. The author recommends reading the connection string explicitly, failing at startup when it is missing, and letting request-scoped services borrow the shared client instead of becoming singletons.
The disposal section is the core of the piece. Disposing MongoClient does not dispose the cluster and its connections; that requires the driver's ClusterRegistry.UnregisterAndDisposeCluster, which can break other clients sharing the cluster if called blindly. Obtaining a database or collection handle proves nothing about connectivity, only a server operation does. The examples are unexecuted and target driver 3.12.0, so verify against your own package version.
Real-world use
- A minimal API in ASP.NET Core where several endpoints read from the same MongoDB database.
- Scoped repository services that serve per-user data but should share one configured MongoClient.
- Hosted background workers that need clean connection shutdown when the application stops.
Why it matters
Separating client lifetime from cluster ownership prevents shutdown code that breaks another client sharing the same infrastructure. Connectivity can only be confirmed with a real server operation, not by successfully building a handle.