ASP.NET Core initialize singleton after configurin

2020-02-26 03:25发布

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

services.AddSingleton<IFoo, Foo>();

And let's say the Foo class has a number of other dependencies (mostly repository classes that allow it to load data).

With my current understanding, the Foo instance is not created until it's first used (asked). Is there a way to initialize this class other than the constructor? Like right after ConfigureServices() completes? Or should the initialization code (loading data from db) be done in Foo's constructor?

(It would be nice if this class could load its data before the first use to speed up first time access)

2条回答
淡お忘
2楼-- · 2020-02-26 03:33

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

查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-26 03:36

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.

查看更多
登录 后发表回答