如何在 asp.net 核心中配置依赖项

how to configure dependencies in asp.net core

我有一个 ASP.Net Core 2.1 应用程序。我需要注册并注入 AWS.

的一些依赖项

目前,实现如下所示:

public abstract class BaseService
{
    protected readonly IConfiguration _configuration;
    protected readonly RegionEndpoint _region;
    protected readonly IAmazonDynamoDB _dynamoClient;
    protected  IPocoDynamo _pocoDynamo;

    public BaseService(IConfiguration configuration)
    {
        _configuration = configuration;
        var awsSettings = configuration.GetSection("AWS");
        _dynamoClient = SetDynamoClient(awsSettings);
        _pocoDynamo = SetPocoDynamoClient();
    }

    protected IAmazonDynamoDB SetDynamoClient(IConfigurationSection configuration)
    {
        AWSCredentials credentials = new BasicAWSCredentials(configuration["AccessKey"], configuration["AccessSecret"]);
        return new AmazonDynamoDBClient(credentials, _region);
    }

    protected IPocoDynamo SetPocoDynamoClient()
    {
        return new PocoDynamo(_dynamoClient);
    }
}

在进行单元测试时,无法模拟 AWS 服务。

我想在 ConfigureServices()

中的 Startup.cs 中注册所有这些依赖项

这就是我正在尝试的:

public void ConfigureServices(IServiceCollection services)
{
    AWSCredentials credentials = new BasicAWSCredentials(configuration["AccessKey"], configuration["AccessSecret"]);

    services.AddTransient(IAmazonDynamoDB, (a) =>
         {
             return new AmazonDynamoDBClient(credentials, RegionEndpoint.GetBySystemName(""))
         });
    // here I need to pass the IAmazonDynamoDB to below IOC
    // services.AddSingleton<IPocoDynamo,new PocoDynamo()> ();

    return services;
}

但是这是一个错误

Error CS0119 'IAmazonDynamoDB' is a type, which is not valid in the given context

这里如何按要求配置依赖?

谢谢!

使用工厂委托调用注册服务

public void ConfigureServices(IServiceCollection services) {
    AWSCredentials credentials = new BasicAWSCredentials(configuration["AccessKey"], configuration["AccessSecret"]);
    services.AddTransient<IAmazonDynamoDB>(sp => 
        new AmazonDynamoDBClient(credentials, RegionEndpoint.GetBySystemName(""))
    );

    //here pass the IAmazonDynamoDB to below IOC
    services.AddSingleton<IPocoDynamo>(serviceProvider => {
        var pocoDynamo = new PocoDynamo(serviceProvider.GetRequieredService<IAmazonDynamoDB>());
        pocoDynamo.SomeMethod();
        return pocoDynamo;
    });
}

目标 class 不再需要依赖于 IConfiguration,因为可以通过构造函数注入显式注入依赖项。

public abstract class BaseService {
    protected readonly IAmazonDynamoDB dynamoClient;
    protected readonly IPocoDynamo pocoDynamo;

    public BaseService(IAmazonDynamoDB dynamoClient, IPocoDynamo pocoDynamo) {        
        this.dynamoClient = dynamoClient;
        this.pocoDynamo = pocoDynamo;
    }
}