Skip to content

Refactor: Inject MongoClient via DI as Singleton #2

@emuuu

Description

@emuuu

Context

Currently EntityContext<TEntity> and MongoRepositoryHealthCheck create MongoClient instances internally. In v10.2.0, a static ConcurrentDictionary<string, MongoClient> cache was added to avoid creating new clients per request, which solves the immediate connection pool waste problem.

However, the proper solution for v11 is to let the DI container manage MongoClient lifetime as a Singleton, allowing consumers to configure client settings (timeouts, SSL, etc.) in one place.

Proposed changes

  • Register MongoClient as a Singleton in DI (keyed by connection string or named options)
  • Inject MongoClient into EntityContext<TEntity> instead of creating it internally
  • Inject MongoClient into MongoRepositoryHealthCheck
  • Remove the static ConcurrentDictionary caches
  • This is a breaking change (constructor signatures change)

Target version

v11.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions