c# - C# IOptions 不能将我的对象隐式转换为接口以将其注入我的服务 AddSingleton
问题描述
我正在学习如何将 MongoDB 与 C# ASP.NET 一起使用,并且我一直在关注 Microsoft 关于使用 MongoDB Mongo Doc Guide的本指南。我已经到了添加配置模型部分的第 3 步,我正在尝试将我的配置接口注入到服务单例中,以便它像指南所说的那样解析我的配置模型的实例。我使用与指南完全相同的代码,只是将我的对象作为它的对象,尽管它一直抛出一个错误,说明Cannot implicitly convert type 'Models.UserDBSettings' to 'Models.IUserDBSettings'. An explicit conversion exists (are you missing a cast?)
. 所以我想知道如何解决这个问题?感谢您提前提供帮助
这是我的代码:
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<UserDBSettings>(
Configuration.GetSection(nameof(UserDBSettings)));
services.AddSingleton<IUserDBSettings>(sp =>
sp.GetRequiredService<IOptions<UserDBSettings>>().Value);
// the line above throws the error and matches this line of code in the guide services.AddSingleton<IBookstoreDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<BookstoreDatabaseSettings>>().Value);
services.AddScoped<UserRepository>();
services.AddControllers();
}
用户数据库设置
public class UserDBSettings
{
public string UserCollectionName { get; set; }
public string ConnectionString { get; set; }
public string DataBaseName { get; set; }
}
public interface IUserDBSettings
{
string UserCollectionName { get; set; }
string ConnectionString { get; set; }
string DataBaseName { get; set; }
}
}
然后我的应用设置包含连接信息:
{
"UserDBSettings": {
"UserCollection": "Users",
"ConnectionString": "mongodb://connectionAdresss",
"DatabaseName": "DBName"
},
解决方案
您需要标记UserDBSettings
为实现IUserDBSettings
接口(请参阅文档),否则它只是 2 种恰好具有相同属性的类型:
public class UserDBSettings : IUserDBSettings
{
public string UserCollectionName { get; set; }
public string ConnectionString { get; set; }
public string DataBaseName { get; set; }
}
推荐阅读
- r - 由于内部编译器错误,无法在 Ubuntu 20.04 中安装某些 R 包:分段错误
- python - 从 python 中的不同类调用 tkinter 应用程序
- python - 带有 CustomUser 的 Django 权限
- php - Gravityforms 在主题 functions.php 中的下拉列表中填充选定值
- angular - Angular2+ e2e 的量角器配置,适用于本地运行和 docker
- reactjs - 在 lineWidth 更改时停止画布清除
- python - 用 get_running_app() 区分继承 App 的类
- python - 在 Windows 浏览器上连接到烧瓶 docker 容器
- solidity - 在solidity中访问继承的变量以覆盖它
- python - 使用 Google Colab 发送邮件