我是ASP.NET Core MVC的新手,并且遇到依赖注入的问题。ASP.NET Core MVC依赖注入问题
我有一个解决方案,我想共享一个EF数据库上下文类的多个项目。我为配置管理器定义了一个接口,这样我就可以跨项目共享通用配置,但也具有项目特定的配置。
运行时的各种API的依赖注入失败,并
"System.InvalidOperationException: Unable to resolve service for type IConfigManager"
错误。
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)
DBContextClass
是我在其他项目中引用的类库项目的一部分。
我不知道为什么它不起作用。有人可以帮助并向我解释这个吗?
的DbContext类
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);
}
}
配置管理器接口和实现类
public interface IConfigManager
{
IAppConfig _config { get; set; }
}
public class ConfigManager : IConfigManager
{
public IAppConfig _config { get; set; }
public ConfigManager(IAppConfig config)
{
}
}
启动方法
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>();
}
难道连合mpile?提供可用于重现问题的[mcve]。 – Nkosi
您不要在配置方法内部构建服务提供者,并且在构建提供者后不添加服务。 –