【问题标题】:ASP.NET Core access service in Startup.cs ConfigureServices methodStartup.cs ConfigureServices 方法中的 ASP.NET Core 访问服务
【发布时间】:2017-10-19 11:42:34
【问题描述】:

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

services.AddScoped<ICustomService, CustomService>();

var sp = services.BuildServiceProvider();

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

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

我做错了什么?

【问题讨论】:

  • 你为什么要这样做?你想达到什么目的?
  • 这似乎是XY problem。您要达到的最终目标是什么?

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


【解决方案1】:

我遇到了这样的问题 - 我有一个我想使用的单例“设置”服务。我通过实际创建一个然后通过允许您指定“提供者”的重载向 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();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2017-05-15
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    相关资源
    最近更新 更多