4

In Microsoft Tutorial that explain How to Create a web API with ASP.NET Core and MongoDB https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-2.2&tabs=visual-studio

They have one Collection in MongoDB "Books", and when we configure connection to connect to this collection we add some codes in Startup.cs

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.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
} 

My question: What if I wan to manipulate with multi collections rather than one "Books"? If I have 3 collections: Books, Anthers and Libraries, Should I add

services.AddSingleton<BookService>();
services.AddSingleton<AntherService>();
services.AddSingleton<LibraryService>();

Also what about 20 collections?

1 Answer 1

1

You can register a single Instance of the IMongoDatabase in your Services container. then you can add Singleton Collections to your services container using the IMongoDatabase Instance.

var client = new MongoClient(connectionString);
var db = client.GetDatabase(dbName);
 
var collectionA = db.GetCollection<Model>(collectionName);
services.AddSingleton<IMongoDatabase, db>();
services.AddSingleton<IMongoCollection, collectionA>();

to use these you would expose your collections to your services via the constructor.

public class SomeService : ISomeService
{
   private readonly IMongoCollection<SomeModel> _someCollection;

   public SomeService (IMongoCollection<SomeModel> someCollection)
   {
      _someCollection = someCollection;
   }
}

Then after that you can access the IMongoCollections through your Services (BookingService, AntherService, LibraryService)

you can also add multiple collections to a single service. which allows multiple collection data manipulation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.