在 Core 3.1 中使用 ASP.NET 单一实例的多个服务



我正在使用数据访问类的存储库方法。所以构造函数看起来像这样:

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 个服务解析到它的事实。

然后在启动时.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'.

然后我在启动时运行了一个小的 Debug.WriteLine(( 脚本.cs以查看是否存在 ILogger 和 IConfiguration 服务。他们做到了。我不确定我在这里做错了什么。

ASP.NET Core 服务容器将自动解析通过构造函数注入的服务依赖项,因此您根本不需要操作配置。构造服务时,构造函数中的任何依赖项都是自动必需的(如您所看到的异常(。

只需注册您的服务

services.AddSingleton<IMongoDbUnitOfWork, MongoDbUnitOfWork>();

最新更新