title: How to use async methods with Dependency Injection
body: <p>I am working on a <strong>.net core (2.2) web application</strong> and have a controller which is responsible to have an <strong>on-demand data sync processing</strong>. For the same, I have kept a button on click of which a call to an async method of a service is triggered. </p>
  
  <p>Internally, this service call processed below actions</p>
  
  <ol>
  <li>Fetches data from database for data sync process </li>
  <li>Split data into batches for batch mode of data sync processing</li>
  <li>Prepare data model for relevant batch data</li>
  <li>Sent prepared data batch to targeted message queue</li>
  </ol>
  
  <p>For interaction with database from within service, <strong>Db-context object was provided using IOC / Dependency Injection i.e. via Constructor</strong>.</p>
  
  <p>In order to identify the issue cause, I make service method calls using numerous ways : </p>
  
  <ul>
  <li>Calling Async Method with Task.Run()</li>
  <li>Calling Async Method without Task.Run()</li>
  <li>Calling Sync Method with Task.Run()</li>
  <li>Calling Async Method with ConfigWait(true)</li>
  </ul>
  
  <p>In all cases, it resulted into no change, still getting the <strong>ObjectDisposedException for DbContext object</strong>. </p>
  
  <blockquote>
    <p>On understanding the scope system of IOC more, it seems to me that
    scope is getting disposed for db-context object once the response is
    provided back to user.</p>
  </blockquote>
  
  <p><strong>Code snippet</strong> with minimal lines is represented below :</p>
  
  <p><strong><em>AzureSearchIndexController.cs</em></strong></p>
  
  <pre><code>public class AzureSearchIndexController : Controller
  {
     [HttpGet]
     public IActionResult StartIndex()
     {
        _azureSearchDataSyncService.StartIndexingAsync(_siteId, _siteName);
     }
  }
  </code></pre>
  
  <p><strong><em>AzureSearchDataSyncService.cs</em></strong></p>
  
  <pre><code>public class AzureSearchDataSyncService : IAzureSearchDataSyncService
  {
     public AzureSearchDataSyncService(JobContext context,
              ICacheHandler&lt;AzureSearchDataSyncModel&gt; cacheHandler,
              AzureJobsTopicBus azureJobsTopicBus)
     {
        _context = context;
        _cacheHandler = cacheHandler;
        _azureJobsTopicBus = azureJobsTopicBus;
        azureSearchDataSyncModel = new AzureSearchDataSyncModel();
     }
  
     public async Task StartIndexingAsync(int siteId, string siteName)
     {
        try
        {
           int fetchedData = 0;
           int _batchSize = 10;
           List&lt;AzureJobMessageModel&gt; azureJobMessages = new List&lt;AzureJobMessageModel&gt;();
  
           var jobsToAdd_Update= GetData(siteId);
           while (dataSyncModel.SyncStatus &amp;&amp; 
              fetchedData &lt; jobsToAdd_Update.Count)
           {
              var batchData = jobsToAdd_Update.Skip(fetchedData)
                            .Take(_batchSize - azureJobMessages.Count)
                            .ToList();
              if (batchData.Count &lt;= 0)
                 continue;
  
              azureJobMessages.AddRange( 
                 PrepareAzureJobMessageModel( 
                        PrepareAzureSearchIndexerModel(batchData), 
                    EntityActionEnum.updated)
              );
  
              fetchedData += batchData.Count();
  
              if (azureJobMessages.Count &gt;= _batchSize)
              {
                 //Method sending batch data
                 await _azureJobsTopicBus.SendMessageAsync(azureJobMessages);
                 dataSyncModel.ProcessedData += azureJobMessages.Count();
                 dataSyncModel.ProcessedBatches += 1;
                 azureJobMessages = new List&lt;AzureJobMessageModel&gt;();
              }
           }
        }
        catch(Exception ex)
        {
            throw ex;
        }
     }
  }
  </code></pre>
  
  <p><strong>Desired Result :</strong> Want to have an async mode of data sync process on button click.</p>
  
  <p><strong>Actual Result :</strong></p>
  
  <blockquote>
    <p>getting error "ObjectDisposedException - Cannot access Disposed Object
    (Db-context)"</p>
  </blockquote>
  
  <p>. Do anyone have any idea on this?</p>
  
  <p><strong>Note:-</strong> I don't want to make action method async. I will be using this method calls either in service methods or CRUD actions which includes CRUD operation logic. I want data sync logic to run in background without affecting the response time for CRUD actions.</p>