title: Web API File Upload Problems
body: <p>Using MVC 4 I'm trying to build a Web API controller where you can upload an image. After the upload is complete the controller should save the image in the database. Here is my code:</p>
  
  <pre><code>[HttpPost]
  public void UploadPhoto(int thirdPartyID)
  {            
      if (!Request.Content.IsMimeMultipartContent())
          throw new Exception(); // divided by zero
  
      byte[] data = null;
      var filename = string.Empty;
  
      var provider = new MultipartMemoryStreamProvider();
      Request.Content.ReadAsMultipartAsync(provider).ContinueWith(y =&gt;
      {
          foreach (var file in provider.Contents)
          {
              filename = file.Headers.ContentDisposition.FileName.Trim('\"');
              data = file.ReadAsByteArrayAsync().Result;                            
          }
  
          var image = this.GetImageFrom(data);            
          var member = this.GetMemberBy(thirdPartyID);
  
          member.ProfileImage = data; 
  
          this.memberService.Save();                        
      });           
  }
  </code></pre>
  
  <p>The problem occurs when the following line executes:</p>
  
  <pre><code>this.memberService.Save();
  </code></pre>
  
  <p>I'm using Ninject and Entity Framework. When this executes I get the error: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. I'm assuming this is happening because the 'ContinueWith' is executing asynchronously within a different request scope than what my DI has bound the original DbContext? Here is my DI bindings for my UOW:</p>
  
  <pre><code>kernel.Bind&lt;IUnitOfWork&gt;().To&lt;UnitOfWork&gt;().InScope(x =&gt; HttpContext.Current);
  </code></pre>
  
  <p>I've read how to change the DI so its scope is bound to an object, but this is a large project and I'm not comfortable at this stage changing the composition root. Does anyone have a work-around that doesn't involve changing the DI? I tried changing the line</p>
  
  <pre><code>Request.Content.ReadAsMultipartAsync(provider).ContinueWith(y =&gt;...
  </code></pre>
  
  <p>to run synchronously with</p>
  
  <pre><code>Request.Content.ReadAsMultipartAsync(provider).RunSynchronously();
  </code></pre>
  
  <p>or</p>
  
  <pre><code>Request.Content.ReadAsMultipartAsync(provider).Wait();
  </code></pre>
  
  <p>The 'RunSynchronously' method gives me an error, the Wait() method just hangs. I just need to upload an image then store it in the database. </p>
  
  <p>EDIT
  Just came acorss this: <a href="https://stackoverflow.com/questions/15201255/request-content-readasmultipartasync-never-returns">Request.Content.ReadAsMultipartAsync never returns</a>. I updated my code based on that post and it fixed my problem!</p>