Technetium
Technetium

Reputation: 6158

Use same implementation for two services with ASP.NET Dependency Injection

I have a ServiceLifetime.Scoped dependency that I only want created once per web request, but it needs to fulfill the request for two services. One of them is an interface that an implementation fulfills, the other is the implementation itself. Right now I'm essentially doing this:

public interface IService {}

public class ServiceImplementation : IService {
    public Object ImplementationSpecificState;
}

public void ConfigureServices(IServiceCollection services) {
    services.AddScoped<IService, ServiceImplementation>();
    services.AddScoped<ServiceImplementation>();
}

Unfortunately, this is giving me two distinct objects with every web request. One in the code that depends on ServiceImplementation, and a different one in the code that depends on IService.

How do I make requests for IService and ServiceImplementation provide the same underlying object?

Upvotes: 0

Views: 361

Answers (1)

Technetium
Technetium

Reputation: 6158

By using the implementationFactory-based extension method, you can dive back into the IServiceProvider's dependency graph to get the implementation when asked for the interface, and you don't even lose compile-time type checking.

public void ConfigureServices(IServiceCollection services) {
    services.AddScoped<ServiceImplementation>();
    services.AddScoped<IService>(
        provider => provider.GetService<ServiceImplementation>()
    );
}

Fancy.

Upvotes: 3

Related Questions