gpt4 book ai didi

c# - Startup.cs中的ASP.NET Core访问服务的ConfigureServices方法

转载 作者:行者123 更新时间:2023-12-02 02:30:07 26 4
gpt4 key购买 nike

我需要访问 Startup.cs 中的ConfigureServices 方法内的服务,我这样做:

services.AddScoped<ICustomService, CustomService>();

var sp = services.BuildServiceProvider();

var service = sp.GetService<ICustomService>(); // this is null

但是上面的 var service 始终为 null。

我做错了什么?

最佳答案

我遇到了这类问题 - 我有一个我想使用的单例“设置”服务。我解决了这个问题,方法是实际创建一个,然后通过重载使用 DI 注册该确切实例,让您指定一个“提供者”,而不是仅仅注册该类,并添加一个很好的大注释来解释这一点:

var settingsService = new SettingsService(_hostingEnvironment);

//Add a concrete settings service which is then registered as the de facto settings service for all time.
//we need to do this as we want to use the settings in this method, and there isn't a satisfactory method to
//pull it back out of the IServiceCollection here (we could build a provider, but then that's not the same provider
//as would be build later... at least this way I have the exact class I'll be using.
services.AddSingleton<ISettingsService, SettingsService>((p) => settingsService);

..
..
..
var thing = settingsService.SomeSettingIWant();

如果您想要的不是单例而是 transient 的,那么我想您可以直接为其创建一个具体的类吗?我知道这可能感觉有点像作弊,但它会很好用......

关于c# - Startup.cs中的ASP.NET Core访问服务的ConfigureServices方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46829086/

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