How to get an instance of IServiceProvider in .NET Core?

后端 未结 6 1710
不知归路
不知归路 2020-12-08 00:03

IServiceProvider is an interface with single method:

object GetService(Type serviceType);

It\'s used to create instances of ty

6条回答
  •  忘掉有多难
    2020-12-08 00:42

    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));
    

提交回复
热议问题