gpt4 book ai didi

c# - ASP.NET Core 中第三方数据上下文的依赖注入(inject)

转载 作者:太空宇宙 更新时间:2023-11-03 23:09:30 26 4
gpt4 key购买 nike

在我的 ASP.NET 核心 Web API 中,我需要使用 MongoDb。到目前为止,以下是我的实现,但我一直在解决依赖问题。

数据上下文:

 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;
}
}

Controller :

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>();
}

现在我得到以下异常

Unable to resolve service for type'CseApi.Repositories.BuyRepository' while attempting to activate'CseApi.Controllers.ValuesController'.

最佳答案

尝试注册如下服务:

public void ConfigureServices(IServiceCollection services) {
services.AddApplicationInsightsTelemetry(Configuration);
services.AddScoped<AppDbContext>();
services.AddScoped<IBuyRepository, BuyRepository>();
services.AddMvc();
// How to add dependencies here
}

评论更新

Controller 代码应如下所示:

private readonly IBuyRepository _buyRepository;
public ValuesController(IBuyRepository buyRepository) {
_buyRepository = buyRepository;
}

关于c# - ASP.NET Core 中第三方数据上下文的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39865924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com