创建AWS初始化类

时间:2018-08-07 19:16:03

标签: c# asp.net-core .net-core-2.0

我有一个连接到我的发电机数据库的API。我的API有很多GET,POST,Delete等终结点。我正在使用以下代码:

var awsCredentials = Helper.AwsCredentials(id, password);
var awsdbClient = Helper.DbClient(awsCredentials, "us-east-2");
var awsContext = Helper.DynamoDbContext(awsdbClient);

List<ScanCondition> conditions = new List<ScanCondition>();
var response = await context.ScanAsync<MyData>(conditions).GetRemainingAsync();

return response.ToList();

我的代码的前三行(即设置awsCredentials,awsdbClient和awsContext)在每个WEB API调用中重复。

这是我的静态助手类:

public static class Helper
{
    public static BasicAWSCredentials AwsCredentials(string id, string password)
    {
        var credentials = new BasicAWSCredentials(id, password);
        return credentials;
    }
    public static AmazonDynamoDBClient DynamoDbClient(BasicAWSCredentials credentials, RegionEndpoint region)
    {
        var client = new DBClient(credentials, region);
        return client;
    }
    public static DynamoDBContext DynamoDbContext(AmazonDynamoDBClient client)
    {
        var context = new DynamoDBContext(client);
        return context;
    }
}

我在API中使用此帮助程序类来初始化AWS。

是否有更好的方法来初始化它?

1 个答案:

答案 0 :(得分:1)

让我们利用ASP.Net内置的依赖注入。

我们需要创建一个快速界面以显示您所需的值。

public interface IDynamoDbClientAccessor
{
    DynamoDBContext GetContext();
}

还有我们稍后将使用的设置类。

public class DynamoDbClientAccessorSettings
{
    public string Id { get; set; }
    public string Password { get; set; }
    public string Region { get; set; }
}

现在是具体的课程。

public class DynamoDbClientAccessor : IDynamoDbClientAccessor
{
    private readonly DynamoDbClientAccessorSettings settings;

    public DynamoDbClientAccessor(IOptions<DynamoDbClientAccessorSettings> options)
    {
        settings = options?.Value ?? throw new ArgumentNullException(nameof(options));
    }

    public DynamoDBContext GetContext()
    {
        // You have the option to alter this if you don't
        // want to create a new context each time. 
        // Have a private variable at the top of this class
        // of type DynamoDBContext. If that variable is not null,
        // return the value. If it is null, create a new value,
        // set the variable, and return it.

        var awsCredentials = Helper.AwsCredentials(settings.Id, settings.Password);
        var awsdbClient = Helper.DbClient(awsCredentials, settings.Region);
        var awsContext = Helper.DynamoDbContext(awsdbClient);

        return awsContext;
    }
}

将所有这些内容都存储在Startup类中

services.AddSingleton<IDynamoDbClientAccessor, DynamoDbClientAccessor>();
services.Configure<DynamoDbClientAccessorSettings>(c =>
{
    c.Id = "YOUR ID";
    c.Password = "YOUR PASSWORD";
    c.Region = "YOUR REGION";
});

现在,在控制器或其他DI服务中,您需要在构造函数中提供一个IDynamoDbClientAccessor实例。

一旦您更加熟悉依赖注入,就可以将更多的东西分解成自己的依赖服务。正如Daniel所说,AWS SDK甚至提供了一些可供您使用的界面,这些界面也可以提供帮助。