对于.NET核心web应用程序,我们通常在
appsettings.json
{
"SASToken": "TOKENHERE",
"StorageAccountPrimaryUri":"CONNECTIONSTRING",
...
}
获取价值appsetting.json,利用注入的IConfiguration对象。
-
public interface ITableStorageAccount { string Method(); }
public class TableStorageAccount : ITableStorageAccount
{
private readonly IConfiguration Configuration;
public TableStorageAccount(IConfiguration configuration)
{
Configuration = configuration;
}
public string Method()
{
string cre = Configuration["SASToken"];
CloudTableClient table = new CloudTableClient(new Uri("xxx"), new StorageCredentials(cre));
return table.BaseUri.AbsolutePath;
}
}
-
中的配置依赖项注入启动.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<ITableStorageAccount, TableStorageAccount>();
}
-
使用控制器中的服务。
private readonly ITableStorageAccount TableStorageAccount;
public MyController(ITableStorageAccount TableStorageAccount)
{
this.TableStorageAccount = TableStorageAccount;
}
在Program.cs 模板。
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
CreateDefaultBuilder()
加载配置的工作是否像appsetting.json文件,请参阅中的更多详细信息
docs