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
:
Is it possible (if so HOW) to get dependency injection with mixed constructors having both injected services and non-injectable parameters?
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...)