在我的ASP.NET核心Web API中,我需要使用MongoDb。以下是我迄今爲止的實現,但我堅持解決依賴關係。ASP.NET核心中第三方數據上下文的依賴注入
的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;
}
我的問題是h流量添加此依賴關係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'。
我不知道,如果它不能正常工作,我需要手動檢查。奇怪的是,mongo db文章沒有經過測試。 – mybirthname
您是否使用NuGet包來添加對MongoDB的支持? – mtaanquist
是''mongocsharpdriver「:」2.3.0「' –