【发布时间】:2023-03-03 20:05:01
【问题描述】:
我正在为数据访问类使用存储库方法。所以构造函数看起来像这样:
public class MongoDbUnitOfWork : IMongoDbUnitOfWork
{
private readonly ILogger _logger;
private readonly IConfiguration _config;
public MongoDbUnitOfWork(ILogger logger, IConfiguration config)
{
_logger = logger;
_config = config
//do other stuff here, create database connection, etc.
}
}
public interface IMongoDbUnitOfWork
{
// various methods go in here
}
关键是构造函数依赖于2个服务被解析到它的事实。
然后在 startup.cs 我尝试执行以下操作:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IMongoDbUnitOfWork>(sp =>
{
var logger = sp.GetRequiredService<ILogger>();
var config = sp.GetRequiredService<IConfiguration>();
return new MongoDbUnitOfWork(logger, config);
});
//add other services
}
当我尝试通过控制器运行 API 路由时,它已编译但不起作用。我收到一条错误消息:
System.InvalidOperationException: Unable to resolve service for type 'NamespaceDetailsHere.IMongoDbUnitOfWork' while attempting to activate 'NamespaceDetailsHere.Controllersv1.TestController'.
然后我在 startup.cs 中运行了一个小 Debug.WriteLine() 脚本来查看 ILogger 和 IConfiguration 服务是否存在。他们做到了。我不确定我在这里做错了什么。
【问题讨论】:
-
您是否尝试过添加所有服务,例如: services.AddSingleton
(); services.AddSingleton (); services.AddSingleton ();
标签: c# asp.net-core asp.net-core-3.1