本文介绍了使用ASP.NET API Core2.1时如何在MongoDB中处理多重集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Microsoft教程中,该教程解释了如何使用ASP.NET Core和MongoDB创建Web API https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-2.2&tabs=visual-studio

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

他们在MongoDB书籍"中有一个Collection,当我们配置连接以连接到该Collection时,我们在Startup.cs中添加了一些代码

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);
} 

我的问题:如果我想操纵多个馆藏而不是一本书"怎么办?如果我有3个馆藏:书籍,花药和图书馆,我应该添加

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>();

那20个收藏又如何呢?

Also what about 20 collections?

推荐答案

您可以在服务"容器中注册IMongoDatabase的单个实例.那么您可以使用IMongoDatabase实例将Singleton Collections添加到您的服务容器中.

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;
   }
}

然后,您可以通过服务(BookingService,AntherService,LibraryService)访问IMongoCollections

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.

这篇关于使用ASP.NET API Core2.1时如何在MongoDB中处理多重集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 11:32