ASP.NET Core initialize singleton after configuring DI

后端 未结 3 716
渐次进展
渐次进展 2020-12-25 11:08

So let\'s say I have a singleton class instance that I register in the DI like this:

services.AddSingleton();

And let\'s s

3条回答
  •  执笔经年
    2020-12-25 11:33

    I made some manager and I need to subscribe to events of the other services. I didn't like doing this in the

    webBuilder.Configure (applicationBuilder => ...
    

    I think it should be in the section

    webBuilder.ConfigureServices ((context, services) => ...
    

    So, here is my answer (test on net.core 3):

    public static IHostBuilder CreateHostBuilder (string [] args) =>
        Host.CreateDefaultBuilder (args)
            .ConfigureWebHostDefaults (webBuilder =>
            {
    
            ...
    
            services.AddSingleton();
    
            var buildServiceProvider = services.BuildServiceProvider();
            var someSingletonService = buildServiceProvider.GetRequiredService ();
    
            ...
            });
      
    

提交回复
热议问题