我尝试实现一个通用存储库和通用上下文以与 mongodb 一起使用。我鼓励的问题是我收到以下错误消息:
无法解析“CommonLibrary.Database.GenericContext”类型的服务
这是我在启动类中配置服务的方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<Settings>(
options =>
{
options.ConnectionString = Configuration.GetSection("MongoDb:ConnectionString").Value;
options.Database = Configuration.GetSection("MongoDb:Database").Value;
});
services.AddTransient(typeof(IGenericContext<>), typeof(GenericContext<>));
services.AddTransient(typeof(IGenericRepository<>), typeof(GenericRepository<>));
}
我的通用上下文类:
public class GenericContext<T> : IGenericContext<T> where T : BaseClass
{
private readonly IMongoDatabase db;
public GenericContext(IOptions<Settings> options)
{
var client = new MongoClient(options.Value.ConnectionString);
db = client.GetDatabase(options.Value.Database);
}
public IMongoCollection<T> Entities => db.GetCollection<T>("Entities");
}
我的通用存储库类:
public class GenericRepository<T> : IGenericRepository<T> where T : BaseClass
{
private readonly GenericContext<T> _context;
public GenericRepository(GenericContext<T> context)
{
_context = context;
}
public async Task<IEnumerable<T>> GetAll()
{
return await _context
.Entities
.Find(_ => true)
.ToListAsync();
}
public Task<T> GetById(string customerId)
{
FilterDefinition<T> filter = Builders<T>.Filter.Eq(m => m.EntityId, customerId);
return _context
.Entities
.Find(filter)
.FirstOrDefaultAsync();
}
public async Task Create(T customer)
{
await _context.Entities.InsertOneAsync(customer);
}
public async Task<bool> Update(T customer)
{
ReplaceOneResult updateResult =
await _context
.Entities
.ReplaceOneAsync(
filter: g => g.Id == customer.Id,
replacement: customer);
return updateResult.IsAcknowledged
&& updateResult.ModifiedCount > 0;
}
public async Task<bool> Delete(string entityId)
{
FilterDefinition<T> filter = Builders<T>.Filter.Eq(m => m.EntityId, entityId);
DeleteResult deleteResult = await _context
.Entities
.DeleteOneAsync(filter);
return deleteResult.IsAcknowledged
&& deleteResult.DeletedCount > 0;
}
}
我的基类:
public class BaseClass
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement]
public string EntityId { get; set; }
}
还有我派生的 Customer 类:
public class Customer : BaseClass
{
[BsonElement]
public string CustomerName { get; set; }
}
您知道为什么我的通用存储库无法实例化吗?这似乎是 GenericContext 的问题,但我看不出在哪里。
谢谢