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

后端 未结 6 1711
不知归路
不知归路 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:38

    To get access to existing DI of ASP.NET Core application e.g. in some controller, you should register it in ConfigureServices method of Startup.cs:

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
       services.AddMvc();
       services.AddSingleton(services);   //  <- here
    
       // ... other DI registrations
       services.AddSingleton();
       services.AddTransient();
    }
    

    After that, you can use it in any resolved objects from DI like this:

    public class FooManager: IFooManager
    {
        private readonly ServiceProvider _di;
    
        public FooManager(IServiceCollection serviceCollection)
        {
            _di = serviceCollection.BuildServiceProvider();
        }
    
        public void Start()
        {
            var w1 = _di.GetRequiredService();  // new instance of FooWorker
            var w2 = _di.GetRequiredService();  // new instance of FooWorker
        }
    }
    

提交回复
热议问题