У меня есть два класса, которые используют вложенные зависимости.Мой класс ExceptionHandler
и JwtHelper
.Startup.cs
звоните ExceptionHandler
.Тогда ExceptionHandler
позвоните JwtHelper
.Но хотя я получил exceptionHandler
в startup.cs
, он выдал ошибку Не удалось разрешить службу для типа 'Hsys.WebToken.JwtHelper' при попытке активировать 'Hsys.ExceptionHandling.ExceptionHandler'
Я добавил зависимости к Startup.cs
.В чем может быть причина этой ошибки?
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddSingleton<IJwtHelper, JwtHelper>();
services.AddSingleton<IExceptionHandler, ExceptionHandler>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IHttpContextAccessor httpContextAccessor)
{
app.UseExceptionHandler(builder => builder.Run(async context =>
{
var error = context.Features.Get<IExceptionHandlerFeature>();
//This line give me error while Getting Required Service
IExceptionHandler exceptionHandler = app.ApplicationServices.GetRequiredService<IExceptionHandler>();
await exceptionHandler.AddApplicationError(context, error);
await context.Response.WriteAsync(error.Error.Message);
}));
app.UseHttpsRedirection();
app.UseMvc();
}
ExceptionHandler.cs
public class ExceptionHandler : IExceptionHandler
{
private readonly JwtHelper jwtHelper;
public ExceptionHandler(JwtHelper jwtHelper)
{
this.jwtHelper = jwtHelper;
}
public async Task AddApplicationError()
{
var userId = jwtHelper.GetValueFromToken("userId");
}
}
JwtHelper.cs
public class JwtHelper : IJwtHelper
{
private readonly IHttpContextAccessor httpContextAccessor;
public JwtHelper(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public string GetValueFromToken(string propertyName)
{
var handler = new JwtSecurityTokenHandler();
var tokens = handler.ReadToken(httpContextAccessor.HttpContext.Request.Headers["Authorization"]) as JwtSecurityToken;
return tokens.Claims.FirstOrDefault(claim => claim.Type == propertyName).Value;
}
}