ASP.NET Core Appsettings best practice for reading values (Injection vs Config Builder)

Seeing how settings is such an ordeal in .NET, I was wondering if there really is a best practice or preferred method for retrieving the values from appsettings.json. Currently using .NET 8.

After doing extensive research on this topic, I have found two ways to get appsettings.json values.

The first way used dependency injection and the binding of the options to a class.

Example

// Appsettings.json

"Position": {
   "Title": "Editor",
   "Name": "Joe Smith"
}


// PositionOptions.cs

public class PositionOptions
{
    public const string Position = "Position";

    public string Title { get; set; } = String.Empty;
    public string Name { get; set; } = String.Empty;
}

// Program.cs

builder.Services.Configure<PositionOptions>(
    builder.Configuration.GetSection(PositionOptions.Position));

// Test Class

public class Test2Model : PageModel
{
    private readonly PositionOptions _options;

    public Test2Model(IOptions<PositionOptions> options)
    {
        _options = options.Value;
    }

    public ContentResult OnGet()
    {
        return Content($"Title: {_options.Title} n" +
                       $"Name: {_options.Name}");
    }
}

As you can see from the example above, the configurations get injected into the constructors and the options parameter. This method worked fine, but what I didn’t like about it was that you cannot instantiate classes with the new SomeClass() keyword, since the constructor has injections such as the configurations.

This made me have to register some of my classes, such as a DBClient class that all it does is check for an open connection, and if its not open, create a new connection and return the instance of the Database Provider. I wanted to make this class abstract and completely independent from Dependencies, but with the config methods above, it did not allow me to do this.

I then changed my appsettings to use a wrapper and a configuration builder from this answer taken from here by @Yusif Karimov Is ConfigurationManager.AppSettings available in .NET Core 2.0?

namespace DemoWeppApp
{
    public static class MyConfigWrapper
    {
        public static IConfigurationRoot AppConfigurations { get; }
        static MyConfigWrapper()
        {
            AppConfigurations = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .Build();
        }
    }
}

As you can see, with this wrapper the values from appsettings.json can be retrieved without having to rely on dependency injections.

Here is my DBClient.cs which I need the connection string from appsettings.json with both methods

DBClient.cs

**// Method One using Config Injections**

public class DBClient 
{
  private DatabaseConfig _options;
  private string _connectionString = string.Empty;

  public DBClient(IOptions<DatabaseConfig> options)
  {
    _options = options.Value;
    connectionString = _options.ConnectionString;
  }

  public SqlConnection GetConnection()
  {
    if (some connection == null)
     return new SqlConection(_connectionString)
  }
}


**// Method two using wrapper with configuration builder**

public class DBClient 
{
  private string _connectionString = MyConfigWrapper.AppConfigurations.GetSection("ConnectionString").Value!;

  public DBClient()
  {
  }

  public SqlConnection GetConnection()
  {
    if (some connection == null)
     return new SqlConection(_connectionString)
  }
}

With the second way, I do not have to register my DBClient.cs class as a Dependency Injected service just to call the method to call the method like so without using new DBClient() and using the injected service in the constructor like so in another class someService.GetConnection. Instead it allows me to instantiate and then call GetConnection like so DBclient db = new DBClient() then db.GetConnection()

Again, is there a preferred way of reading getting values from the appsettings.json file. Even the Docs from microsoft say

The preferred way to read related configuration values is using the options pattern. For example, to read the following configuration values

From here https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-8.0#bind-hierarchical-configuration-data-using-the-options-pattern

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật