title: Is it the right way to use IHttpContextAccessor in a class?
body: <p>I am working on an Asp.Net Core web application running on .NET Core 3.1.</p>
  <p>For a wizard form, I am relying on a <em>User</em> class that holds the data stored in session. As we can access HttpContext from a controller, I had this <em>GetUser()</em> method inside my controller to retrieve session data when necessary :</p>
  <pre><code>private User GetUser()
  {
      var session = HttpContext.Session.GetComplexData&lt;User&gt;(&quot;user&quot;);
  
      if (session == null)
      {
          User user = new User();
          HttpContext.Session.SetComplexData(&quot;user&quot;, user);
      }
      return (User)HttpContext.Session.GetComplexData&lt;User&gt;(&quot;user&quot;);
  }
  </code></pre>
  <p>Then I wanted to move that <em>GetUser()</em> method inside the <em>User</em> class so I used DI to provide that class's ctor with IHttpContextAccessor :</p>
  <pre><code>public class User
  {
      private readonly IHttpContextAccessor _contextAccessor;
  
      public User(IHttpContextAccessor contextAccessor)
      {
          _contextAccessor = contextAccessor;
      }
  
      // fields removed here to keep it short
  
      public User GetUser()
      {
          var session = _contextAccessor.HttpContext.Session.GetComplexData&lt;User&gt;(&quot;user&quot;);
  
          if (session == null)
          {
              User user = new User(_contextAccessor);
              _contextAccessor.HttpContext.Session.SetComplexData(&quot;user&quot;, user);
          }
          return (User)_contextAccessor.HttpContext.Session.GetComplexData&lt;User&gt;(&quot;user&quot;);
      }
  }
  </code></pre>
  <p>But then, in order to use that <em>GetUser()</em> method in my controller(s), I also have to provide this controller's ctor with IHttpContextAccessor as my <em>User</em> needs it to be instantiated :</p>
  <pre><code>public class NewController : Controller
  {
      private readonly IHttpContextAccessor _contextAccessor;
  
      public NewController(IHttpContextAccessor contextAccessor)
      {
          _contextAccessor = contextAccessor;     
      }
  
      [HttpGet]
      public IActionResult Step1()
      {
          // Get session data
          User user = new User(_contextAccessor);  // &lt;--
          user = user.GetUser();
  
          // Other code...
          // ---
          return View(&quot;Step1&quot;);
      }
  }
  </code></pre>
  <p>So my question is... Is it the right way to do it?</p>
  <p>Or shall I just stick with my very first GetMethod() inside the controller without bothering with DI and duplicate it in other controllers if I need to access session there...?</p>
  <p>Or perhaps you can show me something I don't know that would be more a good practice..</p>
  <p>THanks</p>