首页 > 解决方案 > 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"
 },

标签: c#mongodbasp.net-coreappsettings

解决方案


您需要标记UserDBSettings为实现IUserDBSettings接口(请参阅文档),否则它只是 2 种恰好具有相同属性的类型:

public class UserDBSettings : IUserDBSettings
{
    public string UserCollectionName { get; set; }
    public string ConnectionString { get; set; }
    public string DataBaseName { get; set; }
}

推荐阅读