【发布时间】:2021-02-03 20:32:52
【问题描述】:
我正在使用 MongoDB 创建一个 .net 核心 API。
以下是我的 MongoDBSettings.cs
public class MongoDBSettings : IMongoDBSettings
{
public string DatabaseName { get; set; }
public string CollectionName { get; set; }
public string ConnectionString { get; set; }
}
public interface IMongoDBSettings
{
string DatabaseName { get; set; }
string CollectionName { get; set; }
string ConnectionString { get; set; }
}
下面是appsettings.json文件
{
"MongoDBSettings": {
"CollectionName": Collname,
"ConnectionString": connStr,
"DatabaseName": Dbname
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
以下是我的服务类
public class InvoiceService
{
private readonly IMongoCollection<Invoice> _invoice;
public InvoiceService(IMongoDBSettings settings)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_invoice = database.GetCollection<Invoice>(settings.CollectionName);
}
public List<Invoice> Get() =>
_invoice.Find(invoice => true).ToList();
}
以下是我的控制器类
[Route("api/[controller]")]
[ApiController]
public class InvoiceController : ControllerBase
{
private readonly InvoiceService _invoiceService;
public InvoiceController(InvoiceService invoiceService)
{
_invoiceService = invoiceService;
}
[HttpGet]
public ActionResult<List<Invoice>> Get() =>
_invoiceService.Get();
}
下面是我的startup.ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MongoDBSettings>(
Configuration.GetSection(nameof(MongoDBSettings)));
services.AddSingleton<MongoDBSettings>(sp =>
sp.GetRequiredService<IOptions<MongoDBSettings>>().Value);
services.AddSingleton<InvoiceService>();
services.AddControllers();
}
当我运行它时,我收到以下错误:
System.AggregateException: '验证服务时出错 描述符'ServiceType:IDP_API.Services.InvoiceService Lifetime: 单例实施类型:IDP_API.Services.InvoiceService' InvalidOperationException:无法解析类型的服务 尝试激活时出现“IDP_API.Models.IMongoDBSettings” 'IDP_API.Services.InvoiceService'。
我尝试改变
services.AddSingleton<InvoiceService>();
到
services.AddTransient<InvoiceService>();
和
services.AddScoped<InvoiceService>();
但它们都不起作用。
有人可以帮忙吗?
【问题讨论】:
标签: c# asp.net-core asp.net-core-webapi