ASP.NET Core initialize singleton after configuring DI

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

    Do it yourself during startup.

    var foo = new Foo();
    services.AddSingleton(foo);
    

    Or "warm it up"

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

    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

提交回复
热议问题