Search code examples
c#dependency-injectionazure-functionsnuget-packagemediatr

"No service for type 'MediatR.IRequestHandler" on execution Azure Function


I'm using an Azure Function (v4) to upload data to a storage account. I use different project (Class libraries), that implement MediatR to execute commands. My code compilates fine but on runtime my function gives the following error:

error

I have a feeling it has something to do with either NuGet packages or Dependency Injection,but I cannot figure it out. I will add some of my code here to give a little bit of detail.


Azure Function Project

In my function.cs I call mediator

       public ImageLoaderFunction(IMediator mediator)
       {
           _mediator = mediator;
       }
       
        // In my Run() method
        var result = await _mediator.Send(new UploadImageCommand(filestream, blobName));

Startup.cs
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));


Class Library Project

UploadImageCommand.cs
public record UploadImageCommand(FileStream FileStream, string BlobName) : IRequest<bool>;

UploadImageHandler.cs

public class UploadImageHandler : IRequestHandler<UploadImageCommand, bool>
{
    private readonly IMyBlobService _myBlobService;

    public UploadImageHandler(IMyBlobService myBlobService)
    {
        _myBlobService = myBlobService;
    }

    public async Task<bool> Handle(UploadImageCommand request, CancellationToken cancellationToken)
    {
        return await _myBlobService.UploadImageAsync(request.FileStream, request.BlobName);
    }
}

I have tried different approaches of adding MediatR to the services in Startup.cs, but without success.


Solution

  • Comment of @Peter Bons solved my issue:

    Yes, thanks! The handlers seem to be in a different assembly than the function itself. Can you try cfg.RegisterServicesFromAssemblies(typeof(UploadImageHandler).Assembly) instead of cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly())