1

我是ASP.NET Core MVC的新手,并且遇到依赖注入的问题。ASP.NET Core MVC依赖注入问题

我有一个解决方案,我想共享一个EF数据库上下文类的多个项目。我为配置管理器定义了一个接口,这样我就可以跨项目共享通用配置,但也具有项目特定的配置。

运行时的各种API的依赖注入失败,并

"System.InvalidOperationException: Unable to resolve service for type IConfigManager"

错误。

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddl‌​eware[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.Servi‌​ce.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>(); 

} 
+0

难道连合mpile?提供可用于重现问题的[mcve]。 – Nkosi

+0

您不要在配置方法内部构建服务提供者,并且在构建提供者后不添加服务。 –

回答

0

好吧,我终于明白了。最终的结果是:

的DbContext类

public class CustomDbContext : IdentityDbContext<CustomIdentity, CustomRole, string> 
{ 
    private readonly IConfigManager _configManager; 
    public CustomDbContext(DbContextOptions<CustomDbContext> options, IConfigManager configManager) : base(options) 
    { 
     this._configManager = configManager; 
    } 

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    { 
     optionsBuilder.UseSqlite(_configManager._config.ConnectionStrings.FirstOrDefault(c => c.id == "IdentityDatabase").connectionString); 
    } 
} 

启动

public IConfigurationRoot Configuration { get; set; } 
public ConfigManager ConfigManager { get; set; } 
public AppConfig Config { get; set; } 
// This method gets called by the runtime. Use this method to add services to the container. 
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 
public Startup(IHostingEnvironment env) 
{ 
    var builder = new ConfigurationBuilder() 
    .SetBasePath(Directory.GetCurrentDirectory()) 
    .AddJsonFile("appsettings.json") 
    .AddEnvironmentVariables(); 

    this.Configuration = builder.Build(); 
    this.Config = new AppConfig(); 
    this.Configuration.Bind(this.Config); 
    this.ConfigManager = new ConfigManager(this.Config); 
} 

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddSingleton<IConfigManager, ConfigManager>(provider => this.ConfigManager); 
    services.AddDbContext<CustomDbContext>(); 
    services.AddIdentity<CustomIdentity, CustomRole>(config => { 
     config.SignIn.RequireConfirmedEmail = true; 
    }) 
     .AddEntityFrameworkStores<CustomDbContext>() 
     .AddDefaultTokenProviders(); 
    services.AddIdentityServer() 
    .AddInMemoryClients(this.ConfigManager.GetClients()) 
    .AddInMemoryIdentityResources(this.ConfigManager.GetIdentityResources()) 
    .AddInMemoryApiResources(this.ConfigManager.GetApiResources()) 
    .AddTemporarySigningCredential() 
    .AddAspNetIdentity<CustomIdentity>(); 
} 

CONFIGMANAGER

public interface IConfigManager 
{ 
    IAppConfig _config { get; set; } 
} 

public class ConfigManager : IConfigManager 
    { 
     public IAppConfig _config { get; set; } 
     public ConfigManager(IAppConfig config) 
     { 
      this._config = config; 
     } 

    } 
} 
2

在这个阶段,您最好手动创建管理器,将其用于配置,然后将其注册到服务集合中。

更新方面

public class CustomDbContext : IdentityDbContext<CustomIdentity, CustomRole, string> { 
    public CustomDbContext(DbContextOptions<CustomDbContext> options) : base(options) { } 
} 

您还应该配置在启动的上下文。

public void ConfigureServices(IServiceCollection services) { 
    var _configManager = new ConfigManager(_config); //Create new instance 
    services.AddSingleton<IConfigManager>(provider => _configManager); // add as singleton 

    services.AddDbContext<CustomDbContext>(options => 
     options.UseSqlite(_configManager._config.ConnectionStrings.FirstOrDefault(c => c.id == "IdentityDatabase").connectionString) 
    ); 

    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>(); 

} 
+0

谢谢!我也尝试过。它引发相同的错误:失败:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware [0] 执行请求时发生未处理的异常 System.InvalidOperationException:尝试激活时无法解析类型为“NovaSec.Core.IConfigManager”的服务'NovaSec.Core.Contexts.CustomDbContext'。 at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider,ISet'1 callSiteChain,ParameterInfo [] parameters,Boolean throwIfCallSiteNotFound) –

+0

此错误被抛出的位置 – Nkosi

+0

当我在我的应用程序上调用任何控制器时。如果我直接在配置服务中配置DBContextClass,如 services.AddDbContext (options => options.UseSqlite(“Data Source = idenitysource.db”)) 它一切正常。它似乎与不接收configManager对象的CustomDbContext类构造函数有关。 –