Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can MongoDatabase and MongoCollection be singletons

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.

like image 390
Questioning Avatar asked Nov 07 '22 00:11

Questioning


1 Answers

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

like image 64
Mahdi Fadaeddini Avatar answered Nov 13 '22 01:11

Mahdi Fadaeddini