0
//this is UserService file   

 using System.Security.Claims;
    
    namespace _HALKA.Services
    {
        public class UserService : IUserService
        {
            private readonly IHttpContextAccessor _httpContextAccessor;
        
    
            public UserService(IHttpContextAccessor httpContextAccessor)
            {
                _httpContextAccessor = httpContextAccessor;
            }
    
            public string GetMyName()
            {
                var result = string.Empty;
                if (_httpContextAccessor.HttpContext != null)
                {
                    result = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.Name);
                }
                return result;
            }
        }
        }

//this is IUserService file
    namespace _HALKA.Services
    {
        public interface IUserService
        {
            string GetMyName();
         
        }
    }

//And this is program.cs file

builder.Services.AddScoped<IUserService, UserService>();

I got this error from "var app = builder.Build();" :

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: _HALKA.Services.IUserService Lifetime: Scoped ImplementationType: _HALKA.Services.UserService': Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate '_HALKA.Services.UserService'.)'

Ceyda Pak
  • 3
  • 3

1 Answers1

0

Add below Code in Programm.cs file

builder.Services.AddHttpContextAccessor();

Robabeh Ghasemi
  • 422
  • 1
  • 3
  • 11