在 Startup.cs 中解析服务是服务定位器模式吗?

Is resolving a service in Startup.cs a service locator pattern?

我已经阅读 Service Locator: roles vs mechanics by Mark Seemann and I can't decide about something. Is this GetRequiredService method, which is used in ConfigureServices method in Startup.cs (which is the composition root 如果我理解正确),服务定位器:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddScoped<IRepository, MyRepository>();

    services.AddAuthorization(options =>
    {
        var myPolicy = services.BuildServiceProvider()
            .GetRequiredService<IRepository>().GetMyPolicy();

        options.AddPolicy("MyPolicy", policy => policy.AddRequirements(myPolicy));
    });
}

在某些极端情况下,服务定位器是不可避免的。

并非所有框架或库的所有部分都准备好成为依赖注入链的一部分,因此您需要直接使用 IoC 容器来定位整个服务。

尽量避免将服务定位器作为实际应用程序代码的一部分,您有责任在软件架构方面尽最大努力。

正如马克 here 所解释的:

A DI container encapsulated in a Composition Root is not a Service Locator - it's an infrastructure component.

Startup class 是 Composition Root 的一部分。这意味着调用 GetRequiredService 而不是 服务定位器反模式的实现。