title: ASP.NET Web Api, Database connection in Threads
body: <p>I have an issue with using a Database in a thread in my asp.net Application.
  When I want to start my application I want to start a thread called "BackgroundWorker" with it, which runs in the background till the whole application is stopped.</p>
  
  <p>The problem is that I have massive problems with the dbContext in the thread.</p>
  
  <p>I I try to start the walker in my Startup.cs in the methods "ConfigureServices" or "Configure" and then initialize the dbContext in the constructor in the Walker like this "dbContext = new ApplicationContext()" it tells me that the connection is not configured, when I try to operate in the while(true) queue on the database.
  If I write an own Controller for the Walker which receives a ApplicationContext in his constructor and then starts a Thread like this, if i call this controller once with a GET Request:</p>
  
  <pre><code>public BackgroundWorker(ChronicusContext dbContext)
      {
          _dbContext = dbContext;
          _messageService = new MailMessageService();
      }
  
      // GET: api/backgroundworker
      [HttpGet]
      [Route("start")]
      public void StartWorker()
      {
  
          //Thread thread = new Thread(this.DoBackGroundWork);
          Thread thread = new Thread(() =&gt; DoBackGroundWork(this._dbContext));
          thread.Start();
  
      }
  
    public void DoBackGroundWork(ChronicusContext _dbContext)
      {
          while (true)
              {
                  if (_dbContext.PollModels.Any())  //Here is the exception
                  {
                   ...
                  }
              }
  
          }
  </code></pre>
  
  <p>Then I receive an System.ObjectDisposedException that the object is already disposed inside the while (true) queue.</p>
  
  <p>I tried those and similar things in many different ways but allways receive exceptions like these two or that the database connection is closed.</p>
  
  <p>Can somebody help me and tell me, how this works?</p>
  
  <p>Thank you!</p>