I try to setup the DI for a new ASP.NET Core site and I have this code:
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// Get the configuration from the app settings.
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
// Get app settings to configure things accordingly.
var appSettings = Configuration.GetSection("AppSettings");
var settings = new AppSettings();
appSettings.Bind(settings);
services
.AddOptions()
.Configure<AppSettings>(appSettings)
.AddSingleton<IConfigurationRoot>(config)
.AddDbContext<MyDbContext>(builder =>
{
builder.UseSqlServer(config.GetConnectionString("myConn"));
}, ServiceLifetime.Transient, ServiceLifetime.Transient);
services.AddSingleton<ILoadTestCleanUpServiceRepository, LoadTestCleanUpServiceRepository>();
...
Now, the LoadTestCleanUpServiceRepository depends on the MyDbContext:
public class LoadTestCleanUpServiceRepository : ILoadTestCleanUpServiceRepository
{
private readonly MyDbContext _dbContext;
public LoadTestCleanUpServiceRepository(MyDbContext dbContext)
{
_dbContext = dbContext;
}
...
..and the DB Context is this:
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> ctxOptions) : base(ctxOptions)
{
}
}
When I run the application, I get this error:
InvalidOperationException: Unable to resolve service for type 'MyCode.Infrastructure.Common.MyDbContext' while attempting to activate 'MyCode.Infrastructure.LoadTestCleanUpService.LoadTestCleanUpServiceRepository'.
I have tried changing the ServiceLifetime options and adding this extra code:
services.AddTransient<MyDbContext>(sp => new MyDbContext(config));
...but nothing seems to help and I cannot understand why this doesn't work. It does try to construct the repository, but why can't it construct the DB Context too? It doesn't even reach the point where I call UseSqlServer()!
Any ideas?
UPDATE 1:
Hmm... I now see this. Most likely it is related:
UPDATE 2:
I have now :
- Replaced EF 6 with Microsoft.EntityFrameworkCore.SqlServer
- Upgraded to netcoreapp2.2 target framework to solve some conflicting assembly versions.
- Made the repository scoped.
But I still get the same error.

MyDbContextis held captive as a Captive Dependency insideLoadTestCleanUpServiceRepository.