ASP.Net Core 2 无法解析类型的服务

Tas*_*key 5 c# .net-core asp.net-core .net-standard-2.0

我正在尝试注册我自己的自定义选项。我的 ASP.Net 项目 (Kimble.API) 中有一个appsettings.json文件。它看起来像这样:

{
    "NotificationHub": {
        "AccountName": "my-notification-hub-name",
        "ConnectionString": "my-secret-connection-string"
    }
}
Run Code Online (Sandbox Code Playgroud)

在 API 项目引用的我的 .Net Standard 库 (Kimble.Core) 中,我有一个类NotificationHubOptions

public class NotificationHubOptions
{
    public string AccountName { get; set; }
    public string ConnectionString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

回到 API 项目。

在我的Startup.cs文件中,在ConfigureServices方法中,我注册了选项:

services.Configure<NotificationHubOptions>(configuration.GetSection("NotificationHub"));
Run Code Online (Sandbox Code Playgroud)

我检查过,注册确实显示在services集合中。

我的控制器的构造函数如下所示:

public MyController(NotificationHubOptions options)
{
    _notificationHubOptions = options;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试调用控制器上的方法时,总是会出现异常:

System.InvalidOperationException: '尝试激活'Kimble.API.Controllers.MyController'时无法解析'Kimble.Core.Options.NotificationHubOptions'类型的服务。'

在我将NotificationHubOptions班级转移到我的核心项目之前,这一切都奏效了。但是,我不明白为什么这很重要。

juu*_*nas 11

你需要注入IOptions<TOptions>,像这样:

public MyController(IOptions<NotificationHubOptions> options)
{
    _notificationHubOptions = options.Value;
}
Run Code Online (Sandbox Code Playgroud)

当你使用 Configure,您正在注册一个回调以在创建该类型时为其配置选项实例。在这种情况下,使用配置部分将数据绑定到选项对象。

所以选项类本身不在 DI 中。

如果你愿意,你可以这样做:

var options = Configuration.GetSection("NotificationHub").Get<NotificationHubOptions>();
services.AddSingleton<NotificationHubOptions>(options);
Run Code Online (Sandbox Code Playgroud)