【问题标题】:Use Multiple Services for Singleton in ASP.NET Core 3.1在 ASP.NET Core 3.1 中为单例使用多个服务
【发布时间】: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


【解决方案1】:

ASP.NET Core 服务容器会自动解析通过构造函数注入的服务依赖,所以根本不需要动作配置。构造服务时,构造函数中的任何依赖项都是自动需要的(您可以看到例外情况)。

只需注册您的服务

services.AddSingleton<IMongoDbUnitOfWork, MongoDbUnitOfWork>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2020-09-08
    • 2021-08-10
    • 2019-10-22
    • 2022-12-06
    相关资源
    最近更新 更多