public interface IAzureTableConnection {
Task<HttpResponseMessage> UpdateTenantSettings(TenantSettingsModel tenantSettingsModel);
}
IConfiguration
. 相反,在composition根目录中获取所需的内容并将其传递给依赖类。
Startup
private IConfiguration Configuration { get; set; }
public void ConfigureServices(IServiceCollection services) {
//...
var connectionString = Configuration["AzureTableStorageConnectionString"];
var cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient();
services.AddScoped<IAzureTableConnection>(_ => new AzureTableConnection(tableClient));
//...
}
依赖类只需要依赖于配置的
CloudTableClient
public class AzureTableConnection: IAzureTableConnection {
private readonly CloudTableClient tableClient;
public AzureTableConnection(CloudTableClient tableClient) {
this.tableClient = tableClient;
}
private CloudTable TableConnection(string tableName) {
CloudTable cloudTable = tableClient.GetTableReference(tableName);
return cloudTable;
}
public async Task<HttpResponseMessage> UpdateTenantSettings(TenantSettingsModel tenantSettingsModel) {
CloudTable cloudTable = TableConnection("TenantSettings");
var mergeEntity = await cloudTable.ExecuteAsync(TableOperation.Merge(tenantSettingsModel));
//...do something with the result
return new HttpResponseMessage();
}
}
您的控制器将取决于
IAzureTableConnection
public class MyController : Controller {
private readonly IAzureTableConnection tableConnection;
public MyController(IAzureTableConnection tableConnection) {
this.tableConnection = tableConnection;
}
public async Task<IActionResult> MyAction() {
//...
HttpResponseMessage httpResponseMessage = await tableConnection.UpdateTenantSettings(post);
//...
}
}