Description
Describe the feature
Introduce AddKeyedAwsService which allows register multiple services of the same type with different keys. Then those services can be injected into other components using FromKeyedServices
Use case
I have a service which needs to access S3 buckets in different AWS regions. Different components of the service inject IAmazonS3 instances, but those have to be configured differently.
Proposed solution
It could be
AwsOptions optionsA = GetOptionsA();
AwsOptions optionsB = GetOptionsB();
var services = new ServiceCollection();
services.AddKeyedAwsService<IAmazonS3>("s3A", optionsA);
services.AddKeyedAwsService<IAmazonS3>("s3B", optionsB);
// register dependent components
services.AddTransient<DependentA>();
services.AddTransient<DependentB>();
public class DependentA(
[FromKeyedServices("s3A")] IAmazonS3 s3Client)
{
}
public class DependentB(
[FromKeyedServices("s3B")] IAmazonS3 s3Client)
{
}
Such design is aligned with keyed services functionality of Microsoft.Extensions.DependencyInjection:
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionserviceextensions
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.fromkeyedservicesattribute
Other Information
I could implement my own extension methods for my case if Amazon.Extensions.NETCore.Setup.ClientFactory
was public.
I ended up with registering clents using
var region = "eu-central-1";
//...
services.AddKeyedSingleton<IAmazonS3>("s3Key", (_, _) => CreateS3Client(region));
private static IAmazonS3 CreateS3Client(string regionName)
{
var region = RegionEndpoint.GetBySystemName(regionName);
var credentials = FallbackCredentialsFactory.GetCredentials();
return new AmazonS3Client(credentials, region);
}
but it feels hacky, and I assume can cause problems I don't see now.
Acknowledgements
- I may be able to implement this feature request
- This feature might incur a breaking change
AWS .NET SDK and/or Package version used
AWSSDK.Extensions.NETCore.Setup 3.7
Targeted .NET Platform
.NET 8.0
Operating System and version
MacOS Ventura