简体   繁体   中英

Dependency injected IHttpContextAccessor is null

When I try to call this service and the method GetOrganization() within the http context accessor is null. What could cause the problem?

public class ShopService
{
    private static IHttpContextAccessor? _httpContextAccessor;

    public ShopService(IHttpContextAccessor? httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
    public static async Task<Organization?> GetOrganization(EnvironmentType environment)
    {
             string? accessToken;
            if (_httpContextAccessor?.HttpContext != null)
            {
                accessToken = GetToken();
            }
            else
            {
                throw new NotImplementedException();
            }
    
            // ... other unimportant code
    }
}

This calls the method from the service:


                Organization = User?.Identities.FirstOrDefault()?.AuthenticationType switch
                {
                    "Google" => ShopService.GetOrganization(EnvironmentType.Google).Result,
                    // other unimportant code
                    };

I have this in startup: builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped<ShopService>();

Am I missing something why does it not work? Am I supposed to add something in startup, other than the ShopService
service?

Thank you for all your suggestions. I removed the 'static' from the method and added this wherever I needed the service @inject ShopService _shopService

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM