gpt4 book ai didi

c# - 如何使用 ASP.NET Core 仅在一种方法中获得所需的依赖项

转载 作者:太空宇宙 更新时间:2023-11-03 19:49:59 26 4
gpt4 key购买 nike

我已经在 ASP.NET 的内置容器中注册了我的 FooBar 类型。

我的一个操作方法中需要一个实例。如果我在 Controller 的所有操作中都需要它,那么我会将它注入(inject)到构造函数中。但我只在一个操作方法中需要它。

所以在操作方法中,我假设我可以这样做(未经测试):

var service = HttpContext.RequestServices.GetService(typeof(FooService)) as FooService;

但是the docs say那是个坏主意。我同意。

那么我的选择是什么?

最佳答案

您可以使用 FromServices 属性将依赖项注入(inject)操作:

public IActionResult SampleAction([FromServices]FooService fooService)
{
// ...
}

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:

参见官方文档:https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection#action-injection-with-fromservices

关于c# - 如何使用 ASP.NET Core 仅在一种方法中获得所需的依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40604236/

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