gpt4 book ai didi

c# - DependencyInjection : Initialize class, 在被调用之前(必需)?

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:18 25 4
gpt4 key购买 nike

首先,我使用的是微软的依赖注入(inject)包。 (ServiceProvider, ServiceCollection) 目前进展顺利,除了这个问题。

我有类,我像这样注册到我的 DI

this.AddSingleton<IAppWorker, AppWorker>();
this.AddSingleton<IAppController, AppController>();

这些类永远不会被访问,但它们会在其构造函数中调用一个方法。我真的需要显式解析类,并在构造函数之外调用方法吗?

或者有没有办法让它只初始化一个新实例,并在我需要解析它时存储它?我对此很陌生,甚至不知道要搜索什么。

这个有专门的名字吗?还是根本不可能。

最佳答案

您可以在组合根中创建实例,并使用 AddSingleton<TService>(IServiceCollection, TService) 将它们添加到 DI 容器中过载。

Adds a singleton service of the type specified in TService with an instance specified in implementationInstance to the specified IServiceCollection.

var instance1 = new AppWorker();
services.AddSingleton<IAppWorker>(instance1);

var instance2 = new AppController();
services.AddSingleton<IAppController>(instance2);

引用 Dependency injection in ASP.NET Core

关于c# - DependencyInjection : Initialize class, 在被调用之前(必需)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52568423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com