I am working on an upload service API on asp.net core 2 and since I am working with files I am wondering if is it necessary to implement IDispose interface and call Dispose() method after I am done from the object that contains the file or leave it to .net core framework to call garbage collector.
Edit 1: (here's part of my code)
public class UploadFileModel
{
[Required]
public IFormFile FileBinary { get; set; }
[Required]
[MaxLength(50)]
public string Type { get; set; }
}
I would say no, there is no need to do that. Usually Microsoft implements IDisposable on types that need to be disposed like the DbContext from ef-core. The implementation of IFormFile contains a stream, that is being disposed in a finally statement when calling
Task CopyToAsync(Stream target, CancellationToken cancellationToken = default (CancellationToken));
You only need to make sure that you close the stream you pass in.
For example:
public async Task<IActionResult> Index(UploadFileModel requestModel)
{
using (var myMemoryStream = new MemoryStream())
{
requestModel.FileBinary.CopyToAsync(myMemoryStream);
// Use new memory stream (myMemoryStream) here...
} // myMemoryStream is disposed of here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With