繁体   English   中英

在 ASP.NET Core 3.1 中为 Singleton 使用多项服务

[英]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 

}

当我尝试通过 controller 运行 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>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM