'Minimal API Registering Dependencies

I am trying to register dependencies but one thing that is strange is when using specific handlers. For example, take a simple scenario like:

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var handler = new CustomerHandler(); // Compiler error here

app.MapGet("/customers/{id}",
    (
        [FromQuery(Name = "msg")]string? name,
        [FromRoute(Name = "id")]string id) => handler.Get(id, name));
app.Run();

The handler accepts a single item in its constructor..

public class CustomerHandler
{
    private readonly IGetCustomerQuery _getCustomerQuery;

    public CustomerHandler(IGetCustomerQuery getCustomerQuery)
    {
        _getCustomerQuery = getCustomerQuery;
    }

    public async Task<IResult> Get(string id, string name)
    {
        return Results.Ok(new Customer { Id = id, Name = name });
    }
}

I guess what is the "correct" way to specify these dependencies? I would typically use BuildServiceProvider() and use Get<T>() to create the handler but this is not ideal from what I have read. So I guess would the ideal way be to create these instances? Should I forgo the handler approach?

Please note this is a very simple examaple but the implementation of IGetCustomerQuery would take in configuration settings to a DB for example. I guess using the traditional Web API approach this is mitigated in a way.



Solution 1:[1]

New minimal hosting model has new way of handling DI, via WebApplicationBuilder.Services:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<CustomerHandler>(); // register with correct lifetime

builder.Build() will build the service provider and then minimal API's binding mechanism can be used to resolve the handler:

app.MapGet("/customers/{id}",
    (
        [FromQuery(Name = "msg")]string? name,
        [FromRoute(Name = "id")]string id,
        [FromServices]CustomerHandler handler // possibly attribute can be skipped 
    ) => handler.Get(id, name));

P.S.

I would typically use BuildServiceProvider() and use Get<T>() to create the handler

Please never do that.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guru Stron