Home > database >  Declaring connection strings in a class
Declaring connection strings in a class

Time:08-25

I have declared a connection string in appsettings.json as MyString. And I created a class in my controller class called MyConnection.

How should I read the MyString in the class I've created?

My controller class throws an exception at SqlConnection. What are the changes should be done?

public class CRUDController : ControllerBase
    {
        private readonly IOptions<MySQLConnection> _sqlConnection;
        private readonly ILogger<CRUDController> _logger;

        public CRUDController(ILogger<CRUDController> logger , IOptions<MySQLConnection> _sqlConnection)
        {
            _logger = logger;
        }


        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        SearchRequest sr = new SearchRequest();

CodePudding user response:

Here is a template:

public class MyClass
{
    private readonly IConfiguration configuration;

    public MyClass(IConfiguration configuration)
    {
        this.configuration = configuration;
    }

    public string GetMyConnectionString()
        => configuration.GetConnectionString("MyString");
}

CodePudding user response:

So I wouldn't inject just the connection string, this kind of goes against best practice for DI - but if that's what you need to do for this purpose....

Change your dependency injection around - I've gotten hung up on this before.

Your code should be more like this - you don't want the IOptions as the injected type - you want the actual Connection obj you created.

Then pass that object or it's value in the SqlConnection constructor.

public class CRUDController : ControllerBase
{
    private readonly MySQLConnection _sqlConnection;
    private readonly ILogger<CRUDController> _logger;

    public CRUDController(ILogger<CRUDController> logger , IOptions<MySQLConnection> _sqlConnectionOptions)
    {
        _logger = logger;
        _sqlConnection = _sqlConnectionOptions.Value;
    }


    SqlConnection con = new SqlConnection(_sqlConnection);
    SearchRequest sr = new SearchRequest();
  • Related