让我们利用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;
}
}
在你的创业班上把这些都联系起来
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甚至提供了一些接口供您使用,这也有帮助。