gpt4 book ai didi

c# - 如何在 Microsoft.Extensions.DependencyInjection 中注册现有实例?

转载 作者:行者123 更新时间:2023-12-02 18:02:52 25 4
gpt4 key购买 nike

我正在从 Unity Container 迁移我的 .NET 应用程序依赖注入(inject)框架至 Microsoft.Extensions.DependencyInjection .

现在我找不到将接口(interface)的现有实例注册到 serviceCollection 的方法。在 Unity 中,这是可能的:

_unityContainer.RegisterInstance<IInterface>(myObject);

IServiceCollection我只找到了 AddSingleton , AddScoped , AddTransient所有这些都只接受类型。

(我知道这样做一开始可能是不好的做法,但不幸的是它不在我的控制之下。)

最佳答案

AddSingleton<T> 过载接受实现实例,例如:

services.AddSingleton<IInterface>(myObject);

此外,AddScoped<T> 也有重载和 AddTransient<T>接受一个工厂函数作为参数。所以你可以像这样注册你的接口(interface):

services.AddScoped<IInterface>((prov) => myObject);    
services.AddTransient<IInterface>((prov) => myObject);

但是,后者忽略了每个作用域都有一个实例或一个 transient 实例(如果您总是返回相同的实例)的要点——这与单例注册更匹配。这解释了为什么 AddSingleton<T> 有一个特殊的重载。对比 AddScoped<T>AddTransient<T> .

关于c# - 如何在 Microsoft.Extensions.DependencyInjection 中注册现有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73949435/

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