无法解析服务HttpContextAccessor我已经尝试过addsingleton方法

时间:2019-09-02 18:30:11

标签: c# asp.net-core .net-core

我得到这个异常: InvalidOperationException:尝试激活“ Store.Northwind.MvcWebUI.Services.CartSessionService”时,无法解析类型为“ Microsoft.AspNetCore.Http.HttpContextAccessor”的服务。

我试图在启动文件中进行依赖注入,但没有成功

match(df1,df2)

match(df2,df3)

match(df3,df1)
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());
    }
}

0 个答案:

没有答案