C# 无法将IApplicationDbContext注入.net核心中的服务类

C# 无法将IApplicationDbContext注入.net核心中的服务类,c#,asp.net-core,entity-framework-core,C#,Asp.net Core,Entity Framework Core,我有一个类CurrentUserService,它正在从用户声明(令牌)更新角色。 我想在声明中添加一个来自我的数据库的关于该用户的信息 public class CurrentUserService : ICurrentUserService { private readonly ClaimsPrincipal _currentUser; private readonly IApplicationDbContext _context; public CurrentUs

我有一个类
CurrentUserService
,它正在从用户声明(令牌)更新角色。 我想在声明中添加一个来自我的数据库的关于该用户的信息

public class CurrentUserService : ICurrentUserService
{
    private readonly ClaimsPrincipal _currentUser;
    private readonly IApplicationDbContext _context;

    public CurrentUserService(IHttpContextAccessor httpContextAccessor, IApplicationDbContext context)
    {
        _context = context;
    }
}
这是行不通的。然而,如果我从我的ctor中的输入参数中删除
iaapplicationdbContext上下文
,应用程序就会工作

这是我对该服务的注册:

public static void AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
    services.AddDbContext<IdentityContext>(options =>
        options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))
        .EnableSensitiveDataLogging());

    services.AddTransient<IDateTime, MachineDateTime>();
    services.AddTransient<IMailService, SMTPMailService>();

    services.AddScoped<CurrentUserService>();
    services.AddScoped<ICurrentUserService>(x => x.GetRequiredService<CurrentUserService>());
    //services.AddScoped<ICurrentUserService>(x => x.GetRequiredService<IApplicationDbContext>()); I tried something here to add also my ApplicationDbCOntext, but it wont recognize it..
}
publicstaticvoidaddinfrastructure(此IServiceCollection服务,IConfiguration配置)
{
services.AddDbContext(选项=>
options.UseSqlServer(configuration.GetConnectionString(“DefaultConnection”))
.EnableSensitiveDataLogging());
services.AddTransient();
services.AddTransient();
services.addScope();
services.addScope(x=>x.GetRequiredService());
//services.addScope(x=>x.GetRequiredService());我在这里尝试了一些东西来添加我的ApplicationDbCOntext,但它无法识别它。。
}
更新#1

我在此类中有自定义DependencyInjection:

public static class DependencyInjection
{
    public static void AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddDbContext<IApplicationDbContext, ApplicationDbContext>(options =>
        options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))
        .EnableSensitiveDataLogging()); //here I added ApplicationDbContext and its interface

        services.AddDbContext<IdentityContext>(options =>
        options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))
        .EnableSensitiveDataLogging());



        services.AddTransient<IDateTime, MachineDateTime>();
        services.AddTransient<IMailService, SMTPMailService>();

        services.AddScoped<CurrentUserService>();
        services.AddScoped<ICurrentUserService>(x => x.GetRequiredService<CurrentUserService>());

        services.Configure<MailSettings>(configuration.GetSection("MailSettings"));

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            options.SignIn.RequireConfirmedAccount = true;
            options.Password.RequireNonAlphanumeric = false;
        }).AddEntityFrameworkStores<IdentityContext>().AddDefaultUI().AddDefaultTokenProviders();

        services.AddTransient<IIdentityService, IdentityService>();

        //services.AddDefaultIdentity<ApplicationUser>(options =>
        //{
        //    options.User.RequireUniqueEmail = true;
        //    options.Password.RequiredLength = 8;
        //    options.Password.RequireDigit = true;
        //    options.Password.RequireLowercase = true;
        //    options.Password.RequireNonAlphanumeric = true;
        //    options.Password.RequireUppercase = true;
        //});

        services.Configure<JWTSettings>(configuration.GetSection("JWTSettings"));
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
            .AddJwtBearer(o =>
            {
                o.RequireHttpsMetadata = false;
                o.SaveToken = false;
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                    ValidIssuer = configuration["JWTSettings:Issuer"],
                    ValidAudience = configuration["JWTSettings:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWTSettings:Key"]))
                };
                o.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = c =>
                    {
                        c.NoResult();
                        c.Response.StatusCode = 500;
                        c.Response.ContentType = "text/plain";
                        return c.Response.WriteAsync(c.Exception.ToString());
                    },
                    OnChallenge = context =>
                    {
                        context.HandleResponse();
                        context.Response.StatusCode = 401;
                        context.Response.ContentType = "application/json";
                        var result = JsonSerializer.Serialize(Result.Fail("You are not Authorized"));
                        return context.Response.WriteAsync(result);
                    },
                    OnForbidden = context =>
                    {
                        context.Response.StatusCode = 403;
                        context.Response.ContentType = "application/json";
                        var result = JsonSerializer.Serialize(Result.Fail("You are not authorized to access this resource"));
                        return context.Response.WriteAsync(result);
                    },
                };
            });
    }
}
公共静态类依赖注入
{
公共静态void AddInfrastructure(此IServiceCollection服务,IConfiguration配置)
{
services.AddDbContext(选项=>
options.UseSqlServer(configuration.GetConnectionString(“DefaultConnection”))
.EnableSensitiveDataLogging();//我在这里添加了ApplicationDbContext及其接口
services.AddDbContext(选项=>
options.UseSqlServer(configuration.GetConnectionString(“DefaultConnection”))
.EnableSensitiveDataLogging());
services.AddTransient();
services.AddTransient();
services.addScope();
services.addScope(x=>x.GetRequiredService());
services.Configure(configuration.GetSection(“MailSettings”);
服务.附加性(选项=>
{
options.SignIn.RequireConfirmedAccount=true;
options.Password.RequireNonAlphanumeric=false;
}).AddEntityFrameworkStores().AddDefaultUI().AddDefaultTokenProviders();
services.AddTransient();
//services.AddDefaultIdentity(选项=>
//{
//options.User.RequireUniqueEmail=true;
//options.Password.RequiredLength=8;
//options.Password.RequireDigit=true;
//options.Password.RequireLowercase=true;
//options.Password.RequireNonAlphanumeric=true;
//options.Password.RequireUppercase=true;
//});
services.Configure(configuration.GetSection(“JWTSettings”);
services.AddAuthentication(选项=>
{
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o=>
{
o、 RequireHttpsMetadata=false;
o、 SaveToken=false;
o、 TokenValidationParameters=新的TokenValidationParameters
{
ValidateSuersigningKey=true,
validateisuer=true,
ValidateAudience=true,
ValidateLifetime=true,
ClockSkew=TimeSpan.Zero,
ValidisUser=配置[“JWTSettings:Issuer”],
Validudience=配置[“JWTSettings:观众”],
IssuerSigningKey=new-SymmetricSecurityKey(Encoding.UTF8.GetBytes(配置[“JWTSettings:Key”]))
};
o、 事件=新的JWTBeareEvents()
{
OnAuthenticationFailed=c=>
{
c、 诺雷索();
c、 Response.StatusCode=500;
c、 Response.ContentType=“text/plain”;
返回c.Response.WriteAsync(c.Exception.ToString());
},
OnChallenge=context=>
{
context.HandleResponse();
context.Response.StatusCode=401;
context.Response.ContentType=“应用程序/json”;
var result=JsonSerializer.Serialize(result.Fail(“您未经授权”);
返回context.Response.WriteAsync(结果);
},
OnForbidden=上下文=>
{
context.Response.StatusCode=403;
context.Response.ContentType=“应用程序/json”;
var result=JsonSerializer.Serialize(result.Fail(“您无权访问此资源”);
返回context.Response.WriteAsync(结果);
},
};
});
}
}

更有可能的是,
iaapplicationdbcontext
类型尚未在容器中注册

services.AddDbContext<IApplicationDbContext, ApplicationDbContext>(options =>
    //...add connection here        
)
services.AddDbContext(选项=>
//…在此处添加连接
)

上面通过其抽象来注册
ApplicationDbContext
,以便可以根据需要注入它

是的,你是对的,它缺少ApplicationDbContext的一部分。请参阅我的更新#1。然而,我仍然有问题提出这一页。在我的输出窗口中,出现以下错误:
抛出异常:Microsoft.Extensions.DependencyInjection.dll中的“System.UnficientExecutionStackException”
哪一行抛出该错误?
host.Run()错误是什么?你说它不起作用是什么意思