0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hang on! You answered your own question?!?
Yeah, it's within the guidelines. I was stuck for about 20 minutes and posted it, then thought about it a bit more and solved it 10 minutes later. I guess I needed a little rubber duck debugging.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.