Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));
    });
}
like image 708
dstr Avatar asked Aug 31 '25 05:08

dstr


1 Answers

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.

like image 60
Steven Avatar answered Sep 04 '25 04:09

Steven