I've read 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 if I'm understanding it correctly), a service locator:
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));
});
}
As explained by Mark here:
A DI container encapsulated in a Composition Root is not a Service Locator - it's an infrastructure component.
The Startup
class is part of the Composition Root. This implies that calling GetRequiredService
is not an implementation of the Service Locator anti-pattern.