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:
[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 =>
{
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();
});
}
The problem occurs when the following line executes:
this.memberService.Save();
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:
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InScope(x => HttpContext.Current);
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
Request.Content.ReadAsMultipartAsync(provider).ContinueWith(y =>...
to run synchronously with
Request.Content.ReadAsMultipartAsync(provider).RunSynchronously();
or
Request.Content.ReadAsMultipartAsync(provider).Wait();
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.
EDIT Just came acorss this: Request.Content.ReadAsMultipartAsync never returns. I updated my code based on that post and it fixed my problem!