c# - 我应该如何注册使用 MongoClient、Singleton 或作用域的 mongodb 服务?

标签 c# asp.net mongodb

我正在使用 Mongodb 与 ASP.NET core 构建一个 API,并且我有不同的服务 user service home 服务等。我想知道我是否应该将每个服务注册为单例,就像 asp.net core 文档中提到的那样或作为范围。链接到存储库 https://github.com/krisk0su/apartments

UserService.cs

public class UserService
{
    private readonly IMongoCollection<User> _books;
    private readonly IPasswordHasher _passwordService;

    public UserService(IBookstoreDatabaseSettings settings,  IPasswordHasher passwordService)
    {
        var client = new MongoClient(settings.ConnectionString);
        var database = client.GetDatabase(settings.DatabaseName);

        _books = database.GetCollection<User>(settings.UsersCollectionName);
        _passwordService = passwordService;
    }

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

    public User Get(string id) =>
        _books.Find(user => user.Id == id).FirstOrDefault();

    public User Create(User user)
    {
        var password = this._passwordService.HashPassword(user.Password);
        user.Password = password;
        _books.InsertOne(user);
        return user;
    }
    public void Update(string id, User bookIn) =>
        _books.ReplaceOne(book => book.Id == id, bookIn);

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

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

启动.cs

services.AddSingleton<UserService>();
            services.AddSingleton<BookService>();
            services.AddSingleton<AuthenticationService>();
            services.AddScoped<IPasswordHasher, PasswordHasher>();

最佳答案

MongoDB .NET Driver版本 2.17 的引用文档在 Reference > Driver > Connecting 上进行了解释Mongo 客户端中的页面 Re-use部分:

It is recommended to store a MongoClient instance in a global place, either as a static variable or in an IoC container with a singleton lifetime.

关于Mongo数据库Re-use它没有提到单例生命周期,但它确实说它“是线程安全的,并且可以安全地全局存储”,所以我将其解释为意味着它可以安全地存储为单例,如果这就是您的实现所期望的,但如果您更喜欢另一个生命周期,则不需要如此。

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

Mongo Collection 也是如此 Re-use :

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

因此,我再次将其解释为生命周期的选择取决于您的具体要求。

看来只是MongoClient带有使用单例生命周期的建议

关于c# - 我应该如何注册使用 MongoClient、Singleton 或作用域的 mongodb 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59599151/

相关文章:

c# - 当您知道要分配的字段名称时,是否可以将数组分配给未知类型的数组?

c# - 序列化异常 : unexpected character '<'

c# - 将 GitLab Web 应用程序部署到 Azure 应用程序服务

c# - t4 模板相对于 Class 文件的优势

javascript - 从代码后面将变量传递给 javascript 方法

mongodb - 当您在 MongoDB 中管理独立的事物集时,使用多个数据库是否更好?

mongodb - MongoDb 允许的最大嵌入文档深度是多少?

c# - 如果您的错误记录失败,您会怎么做?您如何测试它在生产中的工作情况?

node.js - meteor 方法不起作用

c# - 在 Forms-Authentication 中动态使用 cookie