jonwagner / Insight.Database

Fast, lightweight .NET micro-ORM
Other
861 stars 145 forks source link

Auto-Open but not auto close #389

Closed rokern002 closed 5 years ago

rokern002 commented 5 years ago

Hi, is it possible to configure insight database (6.2.8) have auto open connection but not close it? I would like to use scoped injection in asp.net core 2.1 project on IDbConnection and reuse the connection for the current request in my rest application (scope).

the goal is, let DI container to decide if element should be disposed or not.


        private static IServiceCollection ConfigureDataAccess(this IServiceCollection services)
        {
            const string connectionStringName = "MySql";
            return services
                .AddScoped<IDbConnection>(a=> new MySqlConnection(a.GetService<IConfiguration>().GetConnectionString(connectionStringName)))
                .AddScoped<IUserRepository>(a=>a.GetService<IDbConnection>().As<IUserRepository>())
                //Another Repository
                ;
        }
jonwagner commented 5 years ago

If your DI container opens the connection, then Insight will not close it. There is no close-only mode.

rokern002 commented 5 years ago

I really have to open connection on initialization (addscoped)? what if i have a service call before database access... the service result is invalid, but i already opened the connection even i no need one. kinda inefficient

Jaxelr commented 5 years ago

Insight works by using an IDbConnection, if that connection is passed opened, it will remain open, if the connection is closed, insight will open/close it for you as explained on the wiki. Do you have a specific scenario where it doesnt work as intended? Feel free to post a sample.

jonwagner commented 5 years ago

When we performance-tested the various modes, we found:

Manual open/close is generally used when you have multiple database calls that you want to bind in a transaction.

The general MSFT advice is to rely on the connection pool to do its job, but if you're measuring actual performance problems you can easily write your own wrapper for the DbConnection and do your own open/close semantics.

jonwagner commented 5 years ago

Closing due to inactivity.