Wednesday, June 27, 2018

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 IServiceProviderof course, should be injected using the constructor.

Then the other dependencies can be resolved like the  below source code:

using Microsoft.Extensions.DependencyInjection;

Private IMyClass _myClass;

public MyClass(IServiceProvider serviceProvider)
        {
            _myClass = serviceProvider.GetService(typeof(IMyClass));
            //or 
           _myClass = serviceProvider.GetService<IMyClass>());  
        }