对于开发,我有许多 AWS 配置文件,我使用appsettings.json中的 AWS 配置文件部分来定义我想要使用的配置文件:
"AWS": {
"Profile": "CorpAccount",
"Region": "us-east-1"
}
由于这不是默认配置文件,因此在调试和运行单元测试 (xunit) 时,我需要使用命名配置文件的上下文。我想知道的是配置配置文件的最佳实践是什么。
这是一个展示三种方法的类(两种在本地工作):
public class EmailQueueService : IEmailQueueService
{
private IConfiguration _configuration;
private readonly ILogger _logger;
public EmailQueueService(IConfiguration configuration, ILogger<EmailQueueService> logger)
{
_configuration = configuration;
_logger = logger;
}
public async Task<bool> Add1Async(ContactFormModel contactForm)
{
var sqsClient = new AmazonSQSClient();
var sendRequest = // removed for clarity
var response = await sqsClient.SendMessageAsync(sendRequest);
return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
}
public async Task<bool> Add2Async(ContactFormModel contactForm)
{
var sqsClient = _configuration.GetAWSOptions().CreateServiceClient<IAmazonSQS>();
var sendRequest = // removed for clarity
var response = await sqsClient.SendMessageAsync(sendRequest);
return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
}
public async Task<bool> Add3Async(ContactFormModel contactForm)
{
var sqsClient = new AmazonSQSClient(credentials: Common.Credentials(_configuration));
var sendRequest = // removed for clarity
var response = await sqsClient.SendMessageAsync(sendRequest);
return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
}
public AWSCredentials Credentials(IConfiguration config)
{
var chain = new CredentialProfileStoreChain();
if (!chain.TryGetAWSCredentials(config.GetAWSOptions().Profile, out AWSCredentials awsCredentials))
{
throw new Exception("Profile not found.");
}
return awsCredentials;
}
}
结果:
Add1Async
在本地失败,因为它使用默认配置文件而不是“CorpAccount”。Add2Async
在本地工作,但似乎是一种创建新实例的奇怪方式。Add3Async
在本地工作,但在部署时可能会失败,因为config.GetAWSOptions().Profile
在本地环境之外不存在。
为了完整起见,这是一个单元测试,我从中调用它:
[Fact]
public async void AddAsyncTest()
{
// Arrange
var configuration = TestConfigure.Getconfiguration();
var service = new EmailQueueService(configuration, Mock.Of<ILogger<EmailQueueService>>());
// Act
var result = await service.AddAsync(ContactFormModelMock.GetNew());
// Assert
Assert.True(result);
}
public static IConfiguration Getconfiguration()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
return builder.Build();
}