在我的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“' –