I'm relatively new to ASP.NET Core MVC and am running into issues with dependency injection.
I have a solution with multiple projects in which I want to share a EF database context class. I have defined an interface for a configuration manager so I can share common config across projects, but have project specific config as well.
When running the various API's dependency injection fails with a
"System.InvalidOperationException: Unable to resolve service for type IConfigManager"
error.
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0] An unhandled exception has occurred while executing the request System.InvalidOperationException: Unable to resolve service for type 'NovaSec.Core.IConfigManager' while attempting to activate 'NovaSec.Core.Contexts.CustomDbContext'. at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
The DBContextClass is part of a class library project I reference in the other projects.
I have no idea why it does not work. Can someone please help and explain this to me?
DBContext Class
public class CustomDbContext : IdentityDbContext<CustomIdentity, CustomRole, string>
{
public CustomDbContext(DbContextOptions<CustomDbContext> options, IConfigManager configManager) : base(options)
{
var optionsBuilder = new DbContextOptionsBuilder<CustomDbContext>();
optionsBuilder.UseSqlite(configManager._config.ConnectionStrings.FirstOrDefault(c => c.id == "IdentityDatabase").connectionString);
}
}
Config Manager interface and implementation class
public interface IConfigManager
{
IAppConfig _config { get; set; }
}
public class ConfigManager : IConfigManager
{
public IAppConfig _config { get; set; }
public ConfigManager(IAppConfig config)
{
}
}
Startup Method
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfigManager, ConfigManager>(config =>
{
return new ConfigManager(_config);
});
IServiceProvider serviceProvider = services.BuildServiceProvider();
_configManager = (ConfigManager)serviceProvider.GetService<IConfigManager>();
services.AddDbContext<CustomDbContext>();
services.AddIdentity<CustomIdentity, CustomRole>(config => {
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<CustomDbContext>()
.AddDefaultTokenProviders();
services.AddIdentityServer()
.AddInMemoryClients(_configManager.GetClients())
.AddInMemoryIdentityResources(_configManager.GetIdentityResources())
.AddInMemoryApiResources(_configManager.GetApiResources())
.AddTemporarySigningCredential()
.AddAspNetIdentity<CustomIdentity>();
}