How to use IDbConnection dependency injection and use it in any class?

winanjaya 146 Reputation points
2023-02-27T01:11:04.3833333+00:00

Hi,

I expect to not open/close every time I need to access a table, I learn about IDbConnection dependency injection for PostgreSQL, I have tried the following:

program.cs

builder.Services.AddSingleton<IDbConnection>((sp) => new NpgsqlConnection(Models.AppSettings.PG_SQL.Connection_String));

and in my test class is:

public class Test
    {
        protected IDbConnection _connection;

        protected Test(IDbConnection connection)
        {
            _connection = connection;
        }

        public static async Task MyTest()
        {
            string sqlCount = "select count(0) from sales";
            long ret = _connection.ExecuteScalar<long>(sqlCount, new { });
        }
    }

I expect to call Test.MyTest() since MyTest is a static method

how to accomplish this?

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Rena Ni - MSFT 2,066 Reputation points
    2023-02-27T07:23:40.83+00:00

    Hi @winanjaya,

    It seems the _connection.ExecuteScalar<long> is your customize extension method. Any way, for how to dependency injection in the static class, you could follow like below:

    Program.cs

    builder.Services.AddSingleton<IDbConnection>((sp) => new NpgsqlConnection(Models.AppSettings.PG_SQL.Connection_String));
    var app = builder.Build();
    
    var connection = app.Services.GetRequiredService<IDbConnection>();
    Test.Configure(connection);
    

    Test.cs

    public class Test
    {
        protected static  IDbConnection _connection;
        public static void Configure(IDbConnection connection)
        {
            _connection = connection;
        }
    
        public static async Task MyTest()
        {
            //...        
        }
    }
    

    Call the static class in the controller action

    public class HomeController : Controller
    {
        public async Task Index()
        {
            await Test.MyTest();      
        }
    }
    

    If there has any problem, please let me know freely.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    Rena

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.