在我的ASP.NET核心Web API中,我需要使用MongoDb。以下是我到目前为止的实现,但我仍然坚持解决依赖关系。
的DataContext:
public class AppDbContext
{
public IMongoDatabase MongoDatabase { get; set; }
public AppDbContext()
{
var client = new MongoClient("mongodb://localhost:27017");
MongoDatabase = client.GetDatabase("cse-dev-db");
}
}
存储库:
public class BuyRepository: IBuyRepository {
private readonly AppDbContext _appDbContext;
public BuyRepository(AppDbContext appDbContext) {
_appDbContext = appDbContext;
}
public Buy Add(Buy buy) {
_appDbContext.MongoDatabase.GetCollection<Buy("Buy").InsertOne(buy);
return buy;
}
}
控制器:
private readonly BuyRepository _buyRepository;
public ValuesController(BuyRepository buyRepository) {
_buyRepository = buyRepository;
}
我的问题是如何在ConfigureServices
public void ConfigureServices(IServiceCollection services) {
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
// How to add dependencies here
}
PS:我已经看过this,但它不起作用。
我根据用户的评论尝试了
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddScoped<AppDbContext>();
services.AddMvc();
services.AddScoped<IBuyRepository, BuyRepository>();
}
现在我遇到了异常
无法解析类型的服务 尝试激活时'CseApi.Repositories.BuyRepository' 'CseApi.Controllers.ValuesController'。
答案 0 :(得分:3)
尝试注册以下服务:
public void ConfigureServices(IServiceCollection services) {
services.AddApplicationInsightsTelemetry(Configuration);
services.AddScoped<AppDbContext>();
services.AddScoped<IBuyRepository, BuyRepository>();
services.AddMvc();
// How to add dependencies here
}
更新评论
控制器代码应如下所示:
private readonly IBuyRepository _buyRepository;
public ValuesController(IBuyRepository buyRepository) {
_buyRepository = buyRepository;
}
答案 1 :(得分:0)
通过以下方式更新您的控制器注射:
0
到此:
private readonly BuyRepository _buyRepository;