ASP.NET Core initialize singleton after configuring DI

后端 未结 3 714
渐次进展
渐次进展 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:23

    I got the same problem and I find Andrew Lock blog: https://andrewlock.net/running-async-tasks-on-app-startup-in-asp-net-core-3/

    He explains how to do this with asp .net core 3, but he also refers to his pages on how to to this with previous version.

    0 讨论(0)
  • 2020-12-25 11:28

    Do it yourself during startup.

    var foo = new Foo();
    services.AddSingleton<IFoo>(foo);
    

    Or "warm it up"

    public void Configure(IApplicationBuilder app) 
    {
        app.ApplicationServices.GetService<IFoo>();
    }
    

    or alternatively

    public void Configure(IApplicationBuilder app, IFoo foo) 
    {
        ...
    }
    

    But this feels just dirty and is more a problem with your design, if you do something that you shouldn't in the constructor. Class instantiation has to be fast and if you do long-running operations within it, you break against a bunch of best practices and need to refactor your code base rather than looking for ways to hack around it

    0 讨论(0)
  • 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<ISomeSingletonService,SomeSingletonService>();
    
            var buildServiceProvider = services.BuildServiceProvider();
            var someSingletonService = buildServiceProvider.GetRequiredService <ISomeSingletonService>();
    
            ...
            });
      
    
    0 讨论(0)
提交回复
热议问题