简体   繁体   中英

How to ensure thread safe usage when returning an AmazonS3Client instance from a singleton in .net core

I am trying to abstract away the create of an AmazonS3Client. For context this is done using this mechanism rather than the standard DI mechanism as the credentials needed for the client are only known at runtime after the credentials have been retrieved to assume a role. These credentials have a temporary access token.

I have created the following factory, which aims to return the same client to the caller until the credentials used within the client are invalid. After this I dispose of the client and instantiate a new one.

I want to ensure this is thread safe. As in caller one could have got the client and was about to use it. At the same time caller two tries to get a client, which was then deemed to have invalid credentials. The logic below then tries to dispose of the client. So I am concerned on the impact on caller one.

To add the following code belongs in a singleton service within .net core.

public class AmazonS3ClientFactory : IAmazonS3ClientFactory
{
    private readonly IAmazonAssumeRoleService assumeRoleService;

    private readonly Config config;

    public AmazonS3ClientFactory(
        IOptions<Config> config,
        IAmazonAssumeRoleService assumeRoleService)
    {
        if (string.IsNullOrWhiteSpace(config?.Value.AssumedRoleArn))
        {
            throw new ArgumentNullException(nameof(config));
        }

        this.config = config?.Value;
        this.assumeRoleService = assumeRoleService;
    }

    private IAmazonS3 Client { get; set; }

    public async Task<IAmazonS3> GetClient(RegionEndpoint region)
    {
        if (this.Client != null && this.assumeRoleService.CredentialsExistAndAreValid())
        {
            return this.Client;
        }
        else
        {
            this.Client?.Dispose();

            var credentials= await this.assumeRoleService.AssumeRoleAsync(this.config.AssumedRoleArn);

            this.Client = new AmazonS3Client(assumeRoleCredentials, region);

            return this.Client;
        }
    }
}

yes its thread safe i asked same question from amazon's employee and his answer was yes just enjoy:D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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