最小 API 注册依赖项

Minimal API Registering Dependencies

我正在尝试注册依赖项,但奇怪的是在使用特定处理程序时。例如,以一个简单的场景为例:

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();

处理程序在其构造函数中接受单个项目..

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 });
    }
}

我想指定这些依赖项的“正确”方法是什么?我通常会使用 BuildServiceProvider() 并使用 Get<T>() 来创建处理程序,但从我读到的内容来看这并不理想。所以我想理想的方法是创建这些实例吗?我应该放弃处理程序方法吗?

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.

新的最小托管模型具有处理 DI 的新方法,通过 WebApplicationBuilder.Services:

var builder = WebApplication.CreateBuilder(args);

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

builder.Build() 将构建服务提供者,然后可以使用最小 API 的 binding 机制来解析处理程序:

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

请永远不要那样做。