Resolve Dependency Injection (DI) using IServiceProvider(not in constructor) in .net core mvc (c# , .NET CORE)
Sometime we might need to inject classes which cannot be injected using public constructors (eg. for internal classes/interfaces injection).
For this situation, we can use IServiceProvider and resolve other dependencies using it. By default IServiceProvider, of course, should be injected using the constructor.
Then the other dependencies can be resolved like the below source code:
Private IMyClass _myClass;
public MyClass(IServiceProvider serviceProvider)
{
_myClass = serviceProvider.GetService(typeof(IMyClass));
//or
_myClass = serviceProvider.GetService<IMyClass>());
//or
_myClass = serviceProvider.GetService<IMyClass>());
}