.net core 3.0 获取 IServiceProvider 实例

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

首先,新建一个类:

    public class MyServiceProviderFactory : IServiceProviderFactory<IServiceProvider>
    {
        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<Startup>();
                });
    }

 

posted @ 2020-08-14 20:38  IWing  阅读(357)  评论(0编辑  收藏