为什么在Startup.cs文件中配置了IOption参数值为null

Why is IOption parameter value null when it has been configured in the Startup.cs file

我已经在我的 StartUp.cs 文件中配置了我的 Settings 对象,但是当我将 IOption 传递给 class 时,我在获取连接字符串时遇到空引用异常。

StartUp.cs

        services.Configure<MongoDbSettings>(option =>
        {
            option.ConnectionString = Configuration.GetSection("MongoDbSettings.ConnectionString").Value;
            option.Database = Configuration.GetSection("MongoDbSettings.Database").Value;
        });

实际class

public class BlogPostContext : IBlogPostContext { public IMongoDatabase MongoDatabase { 得到; }

public IMongoCollection<BlogPost> BlogPostModelCollection =>
    MongoDatabase.GetCollection<BlogPost>("BlogPost");

public BlogPostContext(IOptions<MongoDbSettings> settings)
{
    var client = new MongoClient(settings.Value.ConnectionString);
    MongoDatabase = client.GetDatabase(settings.Value.Database);
}

}

我的例外是在这一行

var client = new MongoClient(settings.Value.ConnectionString);

这是一个空引用异常。

我想通了,一个字符错误。而不是

    services.Configure<MongoDbSettings>(option =>
    {
        option.ConnectionString = Configuration.GetSection("MongoDbSettings.ConnectionString").Value;
        option.Database = Configuration.GetSection("MongoDbSettings.Database").Value;
    });

我用过:

    services.Configure<MongoDbSettings>(option =>
    {
        option.ConnectionString = Configuration.GetSection("MongoDbSettings:ConnectionString").Value;
        option.Database = Configuration.GetSection("MongoDbSettings:Database").Value;
    });

我没有意识到我用的是句号而不是冒号