Atish Dipongkor Atish Dipongkor - 1 year ago 94
ASP.NET (C#) Question

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

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'.

Answer Source

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