本文介绍了配置DI后ASP.NET Core初始化单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,假设我有一个单例类实例,我在DI中进行了这样的注册:

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

services.AddSingleton<IFoo, Foo>();

假设Foo类具有许多其他依赖项(主要是允许其加载数据的存储库类).

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

根据我目前的理解,Foo实例是在第一次使用(问)之前才创建的.除了构造函数以外,是否有其他方法可以初始化此类?像ConfigureServices()完成后一样吗?还是应该在Foo的构造函数中完成初始化代码(从db加载数据)?

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)

推荐答案

在启动过程中自行完成.

Do it yourself during startup.

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

或者热身"

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

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

这篇关于配置DI后ASP.NET Core初始化单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:17