Decouple application service from IFormFile

Viewed 510

How to decouple application service from IFormFile without stream copy overhead in asp.net core.

    public interface IUploadService
    {
        Task UploadAsync(IFormFile file, CancellationToken cancellationToken = default);
    }

    [HttpPost]
    public async Task<IActionResult> UploadFile([FromServices] IUploadService uploadService)
    {
        foreach(var file in Request.Form.Files)
        {
            await uploadService.UploadAsync(file);
        }

        return Ok();
    }

I need to decouple UploadAsync method from IFormFile, because application service layer depend on Microsoft.AspNetCore.Http.Features package and I should remove it. A solution is to copy IFormFile to file stream or memory stream and pass stream to UploadAsync method. but this way has stream copy overhead. I need to solution that has not any overhead and decouple application service from IFormFile. for example any way to pass pointer of IFormFile stream and copy stream in UploadAsync method. Thanks.

1 Answers

According to ramin idea.

public interface IFileStream
{
    string Name { get; }

    string FileName { get; }

    string ContentType { get; }

    long Length { get; }

    Task CopyToAsync(Stream target, CancellationToken cancellationToken = default);
}

public interface IUploadService
{
    Task UploadAsync(IFileStream file, CancellationToken cancellationToken = default);
}

and implement proxy in web project.

public class FormFileProxy : IFileStream
{
    private readonly IFormFile file;

    public FormFileProxy(IFormFile file)
    {
        this.file = file ?? throw new ArgumentNullException(nameof(file));
    }

    public string Name => file.Name;

    public string FileName => file.FileName;

    public string ContentType => file.ContentType;

    public long Length => file.Length;

    public async Task CopyToAsync(Stream target, CancellationToken cancellationToken = default)
    {
        await file.CopyToAsync(target, cancellationToken);
    }
}

Then create proxy model and passed it to upload service.

Thanks to all.

Related