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

时间:2016-10-05 05:18:07

标签: c# asp.net mongodb asp.net-core

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

2 个答案:

答案 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;