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

时间:2017-10-19 11:42:34

标签: c# asp.net-core asp.net-core-2.0

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

services.AddScoped<ICustomService, CustomService>();

var sp = services.BuildServiceProvider();

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

但上面的var service始终为空。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我有这样的问题 - 我有一个单身设置&#39;我想用的服务。我通过实际创建一个然后通过重载来注册那个确切的实例来解决它,这个重载允许你指定一个提供者,而不仅仅是注册这个类,并添加一个很好的大评论来解释这个:

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();

如果你想要的不是单身而是短暂的,那么我想你可以在那里创建一个具体的课程吗?我知道这可能感觉有点像作弊,但它会工作得很好......

相关问题