我正在使用 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 aMongoClient
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 aMongoClient
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/