I am following the example here https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-8.0#bind-hierarchical-configuration-data-using-the-options-pattern, but I keep getting the error _options is not null here
and an object reference is required for the non static member, field or property DBProvider.options
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Database": {
"ConnectionString": "my connection stirng"
}
}
public class DatabaseConfig
{
public const string ConfigSection = "Database";
public string ConnectionString { get; set; } = string.Empty;
}
namespace Microsoft.Extensions.DependencyInjection
{
public static class Configs
{
public static IServiceCollection RegisterConfigValues(this IServiceCollection services, IConfiguration config)
{
services.Configure<DatabaseConfig>(
config.GetSection(DatabaseConfig.ConfigSection).GetSection("ConnectinString"));
return services;
}
}
}
//Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services
.RegisterConfigValues(builder.Configuration);
//DBProvider.cs
public class DBProvider
{
private readonly DatabaseConfig _options;
public DBProvider(IOptions<DatabaseConfig> options)
{
_options = options.Value;
}
public static DbConnection GetConnection()
{
DbConnection connection = new SqlConnection(_options.ConnectionString); <------- Getting error here
connection.Open();
return connection;
}
}
I am getting error in the DBProvider.cs
file GetConnection
function