I try to make Options Pattern work for a Microsoft.NET.Sdk project. Following the documentation, the pattern is implemented like so:
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<AzureBlobStorageOptions>(configuration.GetSection("AzureBlobStorage"));
services.AddScoped<IStorageService, AzureBlobStorageService>();
return services;
}
}
Use it:
public class AzureBlobStorageOptions
{
public string ConnectionString { get; set; } = String.Empty;
public string Container { get; set; } = String.Empty;
}
public class AzureBlobStorageService : IStorageService
{
private readonly CloudStorageAccount _storageAccount;
private readonly AzureBlobStorageOptions _options;
public AzureBlobStorageService(IOptions<AzureBlobStorageOptions> options)
{
_options = options.Value;
if (!CloudStorageAccount.TryParse(_options.ConnectionString, out _storageAccount))
{
throw new ArgumentException("Cannot create client from connection string.");
}
}
}
appsettings.json
{
"AzureBlobStorage": {
"ConnectionString": "....",
"Container": "mycontainer"
}
}
I made sure that appsettings.json are always copied. However options.Value is always null. Any ideas what I am missing here? I looked through all SO related topics and this https://github.com/dotnet/AspNetCore.Docs/issues/15940 but could not find a solution.
CodePudding user response:
