Reader

Implementing ServiceLocator in middleware

| Software Engineering Stack Exchange | Default

Before I begin, I'm aware the Service Locator pattern is not recommended and it's better to inject services into the classes where they are used. However, I have a large legacy codebase that creates a lot of objects inside methods without DI. Refactoring this would be a monumental task so I am trying to implement a static Service Locator as reasonably as possible.

My idea is to create a scope as part of a request middleware and set the ServiceLocator instance here. Then allow it to flow through the rest of the request chain before it exists and disposes. I have tested this and my created class is disposed, so it seems to be working as expected. Are there any pitfalls I haven't considered?

public class DependencyLocatorHandler(RequestDelegate next, IServiceProvider serviceProvider)
{
    public async Task InvokeAsync(HttpContext context)
    {
        await using var serviceProviderScope = serviceProvider.CreateAsyncScope();
        ServiceLocator.SetServiceProvider(serviceProviderScope.ServiceProvider);
        await next(context);
    }
}

public static class ServiceLocator
{
    private static IServiceProvider _serviceProvider;

    public static void SetServiceProvider(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public static T GetService<T>()
    {
        return _serviceProvider.GetService<T>();
    }
}