【发布时间】:2019-08-02 03:53:43
【问题描述】:
我已阅读有关该问题的各种文章,并且看起来我们中的很多人都面临过这个问题。我理解这个概念,因为 ChildService 是作用域的,但 FatherService 是单例,它不允许我们运行。
但事实是我将我的服务 IAuthRepository 和 AuthUserContext 添加为 Scoped,因此我不确定它为什么抱怨这个。
我的启动类中的代码是
var userDbConnectionString =Configuration["connectionStrings:userDBConnectionString"];
services.AddDbContext<AuthUserContext>(o =>o.UseSqlServer(userDbConnectionString));
services.AddScoped<IAuthUserRepository, AuthUserRepository>();
在上面的代码中,您可以看到 My DbContext 即 AuthUserContext 添加了 Lifetime as Scoped。同样,IAuthRepository 也被添加为作用域。
有人可以帮忙解释为什么它抱怨低于运行时错误吗?即使我还没有像使用 Singleton 的 Scoped 服务一样。
处理请求时发生未处理的异常。 InvalidOperationException:无法使用范围服务“IDP.Entities.AuthUserContext” 来自单身 'IDP.Services.IAuthUserRepository'
我的存储库类(为简单起见,我删除了其余代码)
public class AuthUserRepository : IAuthUserRepository
{
AuthUserContext _context;
public AuthUserRepository()
{
}
public AuthUserRepository(AuthUserContext context)
{
_context = context;
}
}
我的 AuthUserContext 类
public class AuthUserContext : DbContext
{
public AuthUserContext(DbContextOptions<AuthUserContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<UserClaim> Claims { get; set; }
public DbSet<OtpDetails> OtpDetails { get; set; }
}
我正在使用 Microsoft.AspNetCore.App (2.1.1) 和 IdentityServer4(2.3.2) Nugets
我们将不胜感激。
这是我的配置服务方法
public void ConfigureServices(IServiceCollection services)
{
var userDbConnectionString = Configuration["connectionStrings:userDBConnectionString"];
services.AddDbContext<AuthUserContext>(o => o.UseSqlServer(userDbConnectionString));
services.AddScoped<IAuthUserRepository, AuthUserRepository>();
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddMvc();
services.AddSingleton<IConfiguration>(Configuration);
var identityServerDataDBConnectionString = Configuration["connectionStrings:identityServerDataDBConnectionString"];
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddUserStore()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder => builder.UseSqlServer(identityServerDataDBConnectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder => builder.UseSqlServer(identityServerDataDBConnectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
});
}
我得到的确切异常如下:
处理请求时发生未处理的异常。 InvalidOperationException:无法使用范围服务“CCIDP.Entities.AuthUserContext” 从单例'CCIDP.Services.IAuthUserRepository'
【问题讨论】:
-
您能否发布您的完整方法以及所有服务注册?
-
另外,发布您收到的exact异常。
-
@Isma 我已经编辑了我的原始帖子并更新了您需要的代码。
-
@ChrisPratt 编辑了我的原始帖子并添加了您要求的信息
标签: c# asp.net-mvc asp.net-core identityserver4