How do I use Dependency Injection (.net8) to Inject two MongoBb Clients? I have a scenario where I need to read from Db1/collection1 and then save something to Db2/collection2. In my startup I have the following but not sure how to inject a second IMongoClient (both have different connection string)
services.AddSingleton<IMongoClient>x => new
MongoClient(My_Server_Connection1));
services.AddSingleton<IMongoClient>x => new
MongoClient(My_Server_Connection2));
I would like to be able to do something like this in my DataStore constructor
Db DataStore 1:
public DataStore1(IMongoClient clientWithConStr1, IMongoClient clientWithConStr2)
{
database1 = clientWithConStr1.GetDatabase(DatabaseName1);
database2 = clientWithConStr2.GetDatabase(DatabaseName1);
}
2
Answers
MongoClient
instance is not restricted to use a single database or collection which means that you can operate with as many dbs/collections as you want with a single client. So, I see no reasons to have dedicated instance in your case.Also, even though you create a 2 different MongoClient variables like:
effectively it will be still a single instance as long as provided connection strings are the same. See my answer here for details.
Don’t forget that when you create a mongo client, you effectively create a few background threads and some other shared resources like connection pool which, in turns, holds opened sockets, session pool and so on, so it’s heavy operation and it’s a good idea to reuse it.
However, if you really want to distinguish these clients, configure
ApplicationName
option in MongoClientSettings or connectionString.UPDATE: If your question is only DI related, then consider
Keyed service dependency injection
, see this article:Consuming:
For your scenario to handle multiple
MongoClient
s with different connection strings, it is better to implement a factory to select the MongoClient (provider) by type.MongoClient
by type.MongoClientProvider
by type`.MongoClientProvider
andMongoClientFactory
into DI container.DataStore
class, get theMongoClientFactory
from the DI and retrieve theMongoClient
instance bytype
.