gpt4 book ai didi

c# - 使用 Controller 方法注入(inject) Dotnet 核心方法

转载 作者:太空狗 更新时间:2023-10-29 22:29:42 25 4
gpt4 key购买 nike

假设我在 dotnet 核心中有以下 Controller :

[Route("api/v1/[controller]")]
public class ValuesController : Controller
{
private readonly IHandler<ValuesRequest, ValuesResponse> _valueHandler;
private readonly IHandler<ValuesIdRequest, ValuesIdResponse> _valueIdHandler;

public ValuesController(IHandler<ValuesRequest, ValuesResponse> valueHandler,
IHandler<ValuesIdRequest, ValuesIdResponse> valueIdHandler)
{
_valueHandler = valueHandler;
_valueIdHandler = valueIdHandler;
}

[HttpGet]
public ValuesResponse Get(ValuesRequest request)
{
return _valueHandler.Handle(request);
}

[HttpGet("{id}")]
public ValuesIdResponse Get(ValuesIdRequest request)
{
return _valueIdHandler.Handle(request);
}
}

正如您在上面的代码中看到的,我通过构造函数使用了依赖注入(inject)。但是,我在考虑如何减少代码量。所以,我在考虑使用方法注入(inject),它应该将代码简化为如下所示:

[Route("api/v1/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
public ValuesResponse Get(ValuesRequest request, IHandler<ValuesRequest, ValuesResponse> handler)
{
return handler.Handle(request);
}

[HttpGet("{id}")]
public ValuesIdResponse Get(ValuesIdRequest request, IHandler<ValuesIdRequest, ValuesIdResponse> handler)
{
return handler.Handle(request);
}
}

我想知道是否可以结合 Controller 参数来做这样的事情。我尝试在网上寻找答案,但找不到类似的问题/解决方案。

最佳答案

引用 Action Injection with FromServices

Sometimes you don't need a service for more than one action within your controller. In this case, it may make sense to inject the service as a parameter to the action method. This is done by marking the parameter with the attribute [FromServices] as shown here:

public ValuesResponse Get(ValuesRequest request, [FromServices]IHandler<ValuesRequest, ValuesResponse> handler)
{
return handler.Handle(request);
}

关于c# - 使用 Controller 方法注入(inject) Dotnet 核心方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51671569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com