2016-10-05 79 views
1

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

+0

我不知道,如果它不能正常工作,我需要手動檢查。奇怪的是,mongo db文章沒有經過測試。 – mybirthname

+0

您是否使用NuGet包來添加對MongoDB的支持? – mtaanquist

+0

是''mongocsharpdriver「:」2.3.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; 
} 
+0

它正在拋出異常'嘗試激活'CseApi.Controllers.ValuesController'時無法解析'CseApi.Repositories.BuyRepository'類型的服務。 –

+0

您的控制器應該將'IBuyRepository'而不是'BuyRepository'。查看我的更新。 –

+0

是的這是問題所在。謝謝 –

0

更新您的控制器從該注射液:

private readonly BuyRepository _buyRepository; 

這樣:

private readonly IBuyRepository _buyRepository;