I decided to use MediatR in my Azure Function app. I downloaded MediatR v12.1.1 in my Azure Function project. I have dependent project(class library) with name Services where I have queries(which implement IRequest) and handlers (which implement IRequestHandler<TRequest, TResult>). I added the following rows in Startup.cs of Azure Function project:
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
});
}
My Function:
public class SomeName
{
private readonly IMediator _mediator;
public SomeName(IMediator mediator)
{
_mediator = mediator;
}
[FunctionName("SomeName")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
var tokenString = req.Query["token"];
var token = Guid.Parse(tokenString);
var query = new GetUserDetail(token);
var result = await _mediator.Send(query);
return result != null ? new OkObjectResult(result) : new NotFoundResult();
}
}
As DI Container I use Autofac. When I run my function I get the following error:
System.Private.CoreLib: Exception while executing function: SomeName. Autofac: The requested service 'MediatR.IRequestHandler`2[Some_info]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
How can I fix that error?
Assembly.GetExecutingAssembly()
returns assembly that contains your functions. Mediatr scans it for types that imlementIRequestHandler<,>
interface. Since you have commands and queries in dependant project, this assembly scan results in 0 types found. This means you need to pass different assembly.You may try to register it via
RegisterServicesFromAssemblyContaining<AnyTypeFromYourOtherProject>()
whereAnyTypeFromYourOtherProject
is a type from this project that contains your requestsExample
Folder structure