通常,在.NET Core项目中,我会创建一个“ boostrap”类来配置我的服务以及DI注册命令。这通常是一种扩展方法,IServiceCollection
可以在其中调用类似的方法,.AddCosmosDbService
并且在包含该方法的静态类中,所有必需的东西都是“自包含的”。但是关键是该方法IConfiguration
从Startup
类中。
我过去曾在Azure Functions中使用过DI,但尚未遇到此特定要求。
我正在使用IConfiguration
绑定到属性与我两个都匹配的具体类local.settings.json
当在Azure中部署功能时,以及开发/生产应用程序设置。
CosmosDbClientSettings.cs
/// <summary>
/// Holds configuration settings from local.settings.json or application configuration
/// </summary>
public class CosmosDbClientSettings
{
public string CosmosDbDatabaseName { get; set; }
public string CosmosDbCollectionName { get; set; }
public string CosmosDbAccount { get; set; }
public string CosmosDbKey { get; set; }
}
BootstrapCosmosDbClient.cs
public static class BootstrapCosmosDbClient
{
/// <summary>
/// Adds a singleton reference for the CosmosDbService with settings obtained by injecting IConfiguration
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
/// <returns></returns>
public static async Task<CosmosDbService> AddCosmosDbServiceAsync(
this IServiceCollection services,
IConfiguration configuration)
{
CosmosDbClientSettings cosmosDbClientSettings = new CosmosDbClientSettings();
configuration.Bind(nameof(CosmosDbClientSettings), cosmosDbClientSettings);
CosmosClientBuilder clientBuilder = new CosmosClientBuilder(cosmosDbClientSettings.CosmosDbAccount, cosmosDbClientSettings.CosmosDbKey);
CosmosClient client = clientBuilder.WithConnectionModeDirect().Build();
CosmosDbService cosmosDbService = new CosmosDbService(client, cosmosDbClientSettings.CosmosDbDatabaseName, cosmosDbClientSettings.CosmosDbCollectionName);
DatabaseResponse database = await client.CreateDatabaseIfNotExistsAsync(cosmosDbClientSettings.CosmosDbDatabaseName);
await database.Database.CreateContainerIfNotExistsAsync(cosmosDbClientSettings.CosmosDbCollectionName, "/id");
services.AddSingleton<ICosmosDbService>(cosmosDbService);
return cosmosDbService;
}
}
启动文件
public class Startup : FunctionsStartup
{
public override async void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();
await builder.Services.AddCosmosDbServiceAsync(**need IConfiguration reference**); <--where do I get IConfiguration?
}
}
显然,为IConfiguration
in 添加一个私有字段是Startup.cs
行不通的,因为它需要填充一些东西,而且我还读到,将DI用于IConfiguration
不是一个好主意。
我还尝试过使用此处描述的选项模式,并按如下方式实现:
builder.Services.AddOptions<CosmosDbClientSettings>()
.Configure<IConfiguration>((settings, configuration) => configuration.Bind(settings));
尽管这可以将注入IOptions<CosmosDbClientSettings>
到非静态类中,但我使用的是静态类来保存我的配置工作。
关于如何进行这项工作或可能的解决方法的任何建议?我希望将所有配置都放在一个位置(引导文件)。
host.json
就是没有使用参数,尤其是routePrefix