This question already has an answer here:
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();
}
Aucun commentaire:
Enregistrer un commentaire