In my ASP.NET core Web API, I need to use MongoDb. Following is my implementation so far but I am stuck in resolving dependencies.
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
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.
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'.
"mongocsharpdriver": "2.3.0"IBuyStockRepositoryin theValuesControllerconstructor, not the concrete type.