我是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
您不要在配置方法內部構建服務提供者,並且在構建提供者後不添加服務。 –