5

I am currently working with MongoDriver and, according to the docs, only the MongoClient needs to be a singleton.

That makes sense. However, while researching, I came across some old posts here on SO. The accepted answer (it is 6 years old) here suggests that not only can MongoServer be a singleton but so can the MongoDatabase and the MongoCollection. This, however, is countered by a more recent post (2 years ago) for the Java MongoDriver which suggests only the MongoClient should be a singleton as the other connections can get stale.


My initial thoughts side with the more recent post I linked, that the MongoClient should be the only thing that is a singleton, but considering the conflicting opinions I just wanted to be sure.

Thanks.

Questioning
  • 1,903
  • 1
  • 29
  • 50
  • 1
    *it is 6 years old* - Okay, accepted answers can be wrong.. Just because the term "thread safe" is used does not mean they are singleton instances. The common ( across languages ) pattern is the "connection" ( ie MongoClient ) is or is at least recommended as a singleton. Everything else should simply be an instance in the scope where it is used. – Neil Lunn Nov 06 '18 at 09:08
  • @NeilLunn Thanks for confirming. As I said I did expect the age to play a factor in this. – Questioning Nov 06 '18 at 09:22
  • 1
    Nothing to do with "age", but it's simply incorrect. At no stage was that statement ever true. The only pity is the "referenced documentation" in the external link of the answer no longer exists in order to prove it never said such a thing either. – Neil Lunn Nov 06 '18 at 09:55
  • @NeilLunn ah well. At least the docs + the more recent questions are correct. Thanks for the help. – Questioning Nov 06 '18 at 10:59

1 Answers1

1

I just had same issue and found Microsoft official tutorial, use IMongoCollection as a readonly field in singleton object ,so it's seems there is no problem to use it in singleton way. according to MongoDB official documentation:

The implementation of IMongoCollection ultimately provided by a MongoClient is thread-safe and is safe to be stored globally or in an IoC container.

public class BookService
{
    private readonly IMongoCollection<Book> _books;

    public BookService(IBookstoreDatabaseSettings settings)
    {
        var client = new MongoClient(settings.ConnectionString);
        var database = client.GetDatabase(settings.DatabaseName);
        _books = database.GetCollection<Book>(settings.BooksCollectionName);
    }

    public List<Book> Get() =>
        _books.Find(book => true).ToList();

    public Book Get(string id) =>
        _books.Find<Book>(book => book.Id == id).FirstOrDefault();

    public Book Create(Book book)
    {
        _books.InsertOne(book);
        return book;
    }

    public void Update(string id, Book bookIn) =>
        _books.ReplaceOne(book => book.Id == id, bookIn);

    public void Remove(Book bookIn) =>
        _books.DeleteOne(book => book.Id == bookIn.Id);

    public void Remove(string id) => 
        _books.DeleteOne(book => book.Id == id);
}

and register BookService in service provider

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<BookstoreDatabaseSettings>(
            Configuration.GetSection(nameof(BookstoreDatabaseSettings)));

    services.AddSingleton<IBookstoreDatabaseSettings>(sp =>
        sp.GetRequiredService<IOptions<BookstoreDatabaseSettings>>().Value);

    services.AddSingleton<BookService>();

    services.AddControllers();
    }

https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-5.0&tabs=visual-studio

  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Ran Marciano Dec 17 '20 at 05:39
  • 1
    Mongo Documentation specify explicitly that only MongoClient should be Singleton. MongoDatabase or MongoClient are thread safe and can be stored globally or in a IoC container which I interpret that it is at your decision if you want to make it singleton or not. – Mugurel Dec 21 '20 at 10:53