title: C# Conditionally disposing of Entity Framework DbContext only when needed
body: <p>I'm trying to make my code be intelligent enough to only open and dispose of an Entity Framework DBcontext if it's only needed within the Current execution lifetime of the method in question.</p>
  
  <p>Basically, if a real context is being passed into the method then I do <strong>Not</strong> want to dispose of it.
  However, if it's only needed for the Current execution lifetime of the method in question then it will disposed in the finally block</p>
  
  <pre><code>public int UpSertCompanyStockInfo( Guid companyId, string companyName, float stockPrice, float peRatio, CommunicationEngineDatabase context)
  {
      bool isContextOnlyCreatedForCurrentMethodExecutionRun = false;
      if (context == null)
      {
          isContextOnlyCreatedForCurrentMethodExecutionRun = true;
          context = new CommunicationEngineDatabase();
      }
      try
      {
          CompanyStockInfo companyStockInfo = new CompanyStockInfo();
          companyStockInfo.CompanyName = companyName;
          companyStockInfo.StockPrice = stockPrice;
  
          context.CompanyStockInfoTable.Add(companyStockInfo);
          context.SaveChanges();
      }
      catch (Exception _ex)
      {
  
      }
      finally
      {
          if (isContextOnlyCreatedForCurrentMethodExecutionRun == true &amp;&amp; context != null)
          {
              ((IDisposable)context).Dispose();
          }
  
      }
      return 0;
  
  }
  </code></pre>
  
  <p>The problem is that I feel the aforementioned code is too much in terms of lines of code.  Could someone please tell me how to shorten it( maybe even do it with the using statement)?</p>