.net core 3.0 获取 IServiceProvider 实例

.net core 3.0后,获取IServiceProvider需要绕点弯路

首先,新建一个类:

    public class MyServiceProviderFactory : IServiceProviderFactory
    {
        public IServiceProvider CreateBuilder(IServiceCollection services)
        {
            return Global.ServiceProvider = services.BuildServiceProvider();
        }

        public IServiceProvider CreateServiceProvider(IServiceProvider containerBuilder)
        {
            return containerBuilder;
        }
    }

然后,在CreateHostBuilder里加入 UseServiceProviderFactory(new MyServiceProviderFactory())

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new MyServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup();
                });
    }

 

你可能感兴趣的:(.net core 3.0 获取 IServiceProvider 实例)