简体   繁体   English

ASP.NET核心中第三方数据上下文的依赖注入

[英]Dependency Injection for third party data context in ASP.NET core

In my ASP.NET core Web API, I need to use MongoDb. 在我的ASP.NET核心Web API中,我需要使用MongoDb。 Following is my implementation so far but I am stuck in resolving dependencies. 以下是我到目前为止的实现,但我坚持解决依赖关系。

DataContext: 的DataContext:

 public class AppDbContext
    {
        public IMongoDatabase MongoDatabase { get; set; }
        public AppDbContext()
        {
            var client = new MongoClient("mongodb://localhost:27017");
            MongoDatabase = client.GetDatabase("cse-dev-db");
        }
    }

Repository: 库:

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

My question is how to add this dependencies in ConfigureServices 我的问题是如何在ConfigureServices添加此依赖项

public void ConfigureServices(IServiceCollection services) {
    services.AddApplicationInsightsTelemetry(Configuration);
    services.AddMvc();
    // How to add dependencies here
}

PS: I have already seen this but it does not work. PS:我已经看过这个,但它不起作用。

Update 更新

I have tried as per comment by a user 我根据用户的评论尝试过

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddScoped<AppDbContext>();
            services.AddMvc();
            services.AddScoped<IBuyRepository, BuyRepository>();
        }

Now I am getting following exception 现在我得到以下异常

Unable to resolve service for type 'CseApi.Repositories.BuyRepository' while attempting to activate 'CseApi.Controllers.ValuesController'. 尝试激活'CseApi.Controllers.ValuesController'时,无法解析类型'CseApi.Repositories.BuyRepository'的服务。

Try to register services like: 尝试注册以下服务:

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

Update for comment 更新评论

Controller code should be something like below: 控制器代码应如下所示:

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

Update your controller's injection from this: 从这个更新您的控制器注入:

private readonly BuyRepository _buyRepository;

to this: 对此:

private readonly IBuyRepository _buyRepository;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM