0

I'm trying to add a session in my service

 private readonly ApplicationDbContext _context;
 private readonly ISession _session;


    public CartService(ApplicationDbContext context, IServiceProvider serviceProvider)
    {
        _context = context;
        _session = serviceProvider.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;
    }

and in Startup.cs I added this line:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

When I run the application a get an exception:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

I don't get it, what am I missing?

LittleBird
  • 65
  • 9

1 Answers1

0

I solved it by removing following lines:

 private readonly ISession _session;
 _session = serviceProvider.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;

and instead send a session as a parameter in my method

public List<Item> GetItems(HttpContext httpContext)
    {
     List<Item> Items = new List<Item>();  
        var session = httpContext.Session.GetInt32("Session");

     return Items
    }
LittleBird
  • 65
  • 9