Haha
Haha

Reputation: 167

Read configuration using IOptions<Configuration>

I'm trying to read configuration with options pattern. I want to read a connection string from appsettings given IOptions<Configuration> as injection. I have tried so many ways, but I couldnt figure it out please help.

        private readonly Configuration _config;
        private readonly string _connectionString;

        public QueueClientFactory(IOptions<Configuration> config)
        {
            _config = config.Value;
            var _connectionString = _config.GetSection("Queue:ConnectionString").Get<string>(); //but this is not available in Configuration rather in IConfiguration
}

Upvotes: 0

Views: 962

Answers (1)

haldo
haldo

Reputation: 16701

You should create a class to hold the configuration section you want to use in QueueClientFactory.

Assuming your settings.json looks something like this:

...
"AllowedHosts": "*",  
"Queue": {  
    "ConnectionString": "connection;string;here;",
    "OtherProperty": "Something"
} 
...

Create a model with matching names to bind to the configuration values:

public class QueueClientConfig
{
    public string ConnectionString { get; set; }
    // map any other properties you need
}

And in your Startup.cs/Program.cs class:

public void ConfigureServices(IServiceCollection services)  
{  
    ...
    services.Configure<QueueClientConfig>(_configuration.GetSection("Queue"));
    ...
}

Or if you're using .NET 6:

builder.Services.Configure<QueueClientConfig>(builder.Configuration.GetSection("Queue"));

Then in the QueueClientFactory you can access the configuration values:

private readonly QueueClientConfig queueClientConfig;  

public QueueClientFactory(IOptions<QueueClientConfig> options)  
{  
    queueClientConfig = options.Value;  
}

Alternatively, you should be able to pass IConfiguration to the factory and have DI handle it automatically:

private readonly IConfiguration _config;  
  
public QueueClientFactory(IConfiguration config)  
{  
    _config = config;
    _connectionString = _config.GetSection("Queue:ConnectionString").Get<string>();
}

Upvotes: 4

Related Questions