ASP.NET 启动中的核心访问服务.cs配置服务方法



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

services.AddScoped<ICustomService, CustomService>();
var sp = services.BuildServiceProvider();
var service = sp.GetService<ICustomService>(); // this is null

但是,上述var service始终为空。

我做错了什么?

我遇到了这种问题 - 我有一个我想使用的单例"设置"服务。 我通过实际创建一个然后通过重载向 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();

如果你想要的不是单例,而是瞬态的东西,那么我想你可以在那里为它创建一个具体的类? 我知道这可能感觉有点像作弊,但它会很好用......

最新更新