Home > Software engineering >  IOptions with Connection string
IOptions with Connection string

Time:12-21

I have very simple appsettings:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=test;Database=test;Trusted_Connection=True;"
  },
  "AllowedHosts": "*"
}

Class for connection string:

public class ConnectionStrings
    {
      public string DefaultConnection { get; set; }
    }

I register in DI it like this:

builder.Services.AddOptions<ConnectionStrings>(builder.Configuration.GetConnectionString("DefaultConnection"));

I inject IOption in constructor, but it is always null:

public class ShoppingCartRepository : IShoppingCartRepository
  {
    private readonly IOptions<ConnectionStrings> _connectionStrings;

    public ShoppingCartRepository(IOptions<ConnectionStrings> connectionStrings)
    {
      _connectionStrings = connectionStrings;
    }

    // ...
 
    }
  }

Can I use IOptions for connection string or I should use another approach?

What is best way of working with connection string?

CodePudding user response:

The AddOptions method accept an argument of type string that is the name of the options instance. But You pass the value of DefaultConnection in appsettings.json to it.

You should add Bind method after AddOptions

builder.Services
    .AddOptions<ConnectionStrings>()
    .Bind(Configuration.GetSection("ConnectionStrings:DefaultConnection");

CodePudding user response:

Let's take it from here:

builder.Services.Configure<ConnectionStrings>(
    builder.Configuration.GetSection("ConnectionStrings")
)
  • Related