2016-10-05 43 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;