3

I get this exception: InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.HttpContextAccessor' while attempting to activate 'Store.Northwind.MvcWebUI.Services.CartSessionService'.

I tried to dependency injection in startup file but didn't work

public interface ICartSessionService
{
    Cart GetCart();
    void SetCart(Cart cart);
}

public class CartSessionService : ICartSessionService
{
    private HttpContextAccessor _httpContextAccessor;

    public CartSessionService(HttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public Cart GetCart()
    {
        Cart cartToCheck =  _httpContextAccessor.HttpContext.Session.GetObject<Cart>("cart");
        if (cartToCheck == null)
        {
            _httpContextAccessor.HttpContext.Session.SetObject("cart",new Cart());
            cartToCheck = _httpContextAccessor.HttpContext.Session.GetObject<Cart>("cart");
        }

        return cartToCheck;
    }

    public void SetCart(Cart cart)
    {
        _httpContextAccessor.HttpContext.Session.SetObject("cart", new Cart());
    }
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IProductService, ProductManager>();
    services.AddScoped<IProductDal, EfProductDal>();
    services.AddScoped<ICategoryService, CategoryManager>();
    services.AddScoped<ICategoryDal, EfCategoryDal>();
    services.AddSingleton<ICartSessionService, CartSessionService>();
    services.AddSingleton<ICartService, CartService>();
    services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();
    services.AddSession();
    services.AddDistributedMemoryCache();
    services.AddMvc();
}
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
yasingulec
  • 33
  • 1
  • 6
  • 9
    You register `IHttpContextAccessor` as the service but attempt to resolve `HttpContextAccessor`. Update your `CartSessionService` class to use `IHttpContextAccessor` (with the `I` prefix). – Kirk Larkin Sep 03 '19 at 09:05
  • Spent hours on this and this comment saved my day. worst typo ever. Thank you. – FLICKER Dec 28 '22 at 08:52

0 Answers0