gpt4 book ai didi

c# - HttpContext.RequestServices.GetService() 与 services.AddScope()?

转载 作者:行者123 更新时间:2023-12-03 20:27:08 27 4
gpt4 key购买 nike

在以下代码中(来自 https://github.com/JasonGT/NorthwindTraders/blob/master/Src/WebUI/Controllers/BaseController.cs),它是所有 Controller 继承的基本控件。

[ApiController]
[Route("api/[controller]/[action]")]
public abstract class BaseController : ControllerBase
{
private IMediator _mediator;

protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();
}

然后子类 Controller 只使用 Mediator 的属性.

它与仅添加 services.AddScope<Mediator>(); 有何不同?在 Startup.cs然后注入(inject) mediator .
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// services.AddSingleton<Mediator>();
services.AddScope<Mediator>();

最佳答案

不同的是不需要注入(inject)IMediator到 BaseController 的构造函数 到 BaseController 的所有子类。

所以它节省了一些样板,但也使依赖关系不那么明确。

旁注,Microsoft 建议优先使用注入(inject)而不是 RequestServices

The services available within an ASP.NET Core request from HttpContext are exposed through the HttpContext.RequestServices collection.

Request Services represent the services configured and requested as part of the app. When the objects specify dependencies, these are satisfied by the types found in RequestServices, not ApplicationServices.

Generally, the app shouldn't use these properties directly. Instead, request the types that classes require via class constructors and allow the framework inject the dependencies. This yields classes that are easier to test.

Note

Prefer requesting dependencies as constructor parameters to accessing the RequestServices collection.



Microsoft docs

关于c# - HttpContext.RequestServices.GetService<T>() 与 services.AddScope<T>()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59041523/

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