我已在Settings
文件中配置了StartUp.cs
对象,但是当我将IOption传递给某个类时,获取连接字符串时会得到空引用异常。
StartUp.cs
services.Configure<MongoDbSettings>(option =>
{
option.ConnectionString = Configuration.GetSection("MongoDbSettings.ConnectionString").Value;
option.Database = Configuration.GetSection("MongoDbSettings.Database").Value;
});
实际课程
public class BlogPostContext:IBlogPostContext { public IMongoDatabase MongoDatabase {get; }
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);
这是一个空引用异常。
答案 0 :(得分:1)
我想通了,单个字符错误。而不是
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;
});
我没有意识到我使用的是句号而不是冒号