gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:27:30 25 4
gpt4 key购买 nike

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

{
"NotificationHub": {
"AccountName": "my-notification-hub-name",
"ConnectionString": "my-secret-connection-string"
}
}

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

public class NotificationHubOptions
{
public string AccountName { get; set; }
public string ConnectionString { get; set; }
}

回到 API 项目。

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

services.Configure<NotificationHubOptions>(configuration.GetSection("NotificationHub"));

我已经检查过,注册确实出现在 services 集合中。

我的 Controller 的构造函数如下所示:

public MyController(NotificationHubOptions options)
{
_notificationHubOptions = options;
}

但是,当我尝试调用 Controller 上的方法时,我总是遇到异常:

System.InvalidOperationException: 'Unable to resolve service for type 'Kimble.Core.Options.NotificationHubOptions' while attempting to activate 'Kimble.API.Controllers.MyController'.'

在我将 NotificationHubOptions 类移动到我的核心项目之前,这一切都有效。但是,我完全不明白为什么这很重要。

最佳答案

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

public MyController(IOptions<NotificationHubOptions> options)
{
_notificationHubOptions = options.Value;
}

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

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

如果你想,你可以这样做:

var options = Configuration.GetSection("NotificationHub").Get<NotificationHubOptions>();
services.AddSingleton<NotificationHubOptions>(options);

关于c# - ASP.Net Core 2 无法解析类型的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48549618/

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