0

I want to inject IServiceProvider (and possibly some other services) into a service and/or a custom class whose constructor takes OTHER non-injectable parameters.

Here is an example of what my service/class would look like:

public class MyService {
    IServiceProvider _sProvider;
    /*possibly other injectable services*/
    public MyService(object someCustomStuff, IServiceProvider sProvider) {
        // --- keep reference for later use in methods...
        _sProvider = sProvider;
    }

}

Note that if I am able to access IServiceProvider, I can then retrieve any service I need on the fly using _sProvider.GetService(typeof(MyRequiredService)) so I don't necessarily have to inject other services here.

Still, my requirement is to somehow use injection here.

For a service registered in Startup.ConfigureServices. The default services.AddSingleton<MyService>() throws an error as the injection is not able to retrieve the first someCustomStuff parameter as a service (and I don't want it to be one!). I actually tried the alternative way to register the service using the constructor explicitely :

services.AddSingleton(new MyService(myCustomStuff, _?IServiceProvider?_));

but I don't know how to access IServiceProvider in Startup.ConfigureServices explicitely...

This naturally leads to a more general question about constructor injection for non-component classes and in other places than Startup.ConfigureServices:

  1. Is it possible (if so HOW) to get dependency injection with mixed constructors having both injected services and non-injectable parameters?

  2. Is it possible (if so HOW) to use dependency injection via constructor in code where I do NOT have explicit access to the services to be injected (if I do, as for e.g. in components, it is trivial as I can easly inject the required services to the component and then forward them to the constructor explicitely...)

neggenbe
  • 1,697
  • 2
  • 24
  • 62

1 Answers1

1

For part 1, the answer is to use the provided delegate approach:

services.AddSingleton<MyService>(provider => new MyService(myCustomStuff, provider));

To pass other injected dependencies in the constructor, get them from the provider (make sure the service is already registered, of course):

services.AddSingleton<MyService>(
    provider => 
        new MyService(myCustomStuff, provider.GetService<MyOtherService>())
);

Credits to this post

neggenbe
  • 1,697
  • 2
  • 24
  • 62