在 ASP.NET Core 3.1 中为单例使用多个服务

Use Multiple Services for Singleton in ASP.NET Core 3.1

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

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 服务是否存在。他们做到了。我不确定我在这里做错了什么。

ASP.NET核心服务容器会自动解析通过构造函数注入的服务依赖,所以你根本不需要动作配置。构建服务时,构造函数中的任何依赖项都是自动需要的(正如您可以看到的异常)。

只需使用

注册您的服务
services.AddSingleton<IMongoDbUnitOfWork, MongoDbUnitOfWork>();