IServiceProvider is an interface with single method:
object GetService(Type serviceType);
It\'s used to create instances of ty
As goaty mentioned it's enough to create new ServiceCollection. Here's example class which can be used to access DI container in .NET Core:
public static class ServiceProviderFactory
{
public static IServiceProvider ServiceProvider { get; }
static ServiceProviderFactory()
{
HostingEnvironment env = new HostingEnvironment();
env.ContentRootPath = Directory.GetCurrentDirectory();
env.EnvironmentName = "Development";
Startup startup = new Startup(env);
ServiceCollection sc = new ServiceCollection();
startup.ConfigureServices(sc);
ServiceProvider = sc.BuildServiceProvider();
}
}
Startup class is taken from tested project so the service registrations don't need to be repeated.
Then in test class simply use:
var foo = ServiceProviderFactory.ServiceProvider.GetServices(typeof(IFoo));