ConnectionFactory creating too many connections from .net core registered service

-3

I have inserted a connection factory based LinqToDB service in the .Net Core.

Startup.cs

services.AddScoped<IDatabase, Database>( provider =>
                {
                    IConfigurationSection sqlConfig = Configuration.GetSection("Database");
                    IDataProvider dataProvider = new SqlServerDataProvider("SqlServer", SqlServerVersion.v2008);

                    return new Database(dataProvider,
                        new WorkspaceConnectionFactory(
                        sqlConfig["clientId"],
                        sqlConfig["clientSecret"],
                        sqlConfig["authority"],
                        sqlConfig["target"],
                        sqlConfig["connectionString"]).createConnection());
                });

with this implementation of factory

namespace Workspace.Common.LinqToDB
{
    public class WorkspaceConnectionFactory
    {
        private ClientCredential ClientCredential;
        private string Authority;
        private string Target;
        private string ConnectionString;

        public WorkspaceConnectionFactory(string clientId, string clientSecret, string authority, string target, string connectionString)
        {
            ClientCredential = new ClientCredential(clientId, clientSecret);
            Authority = authority;
            Target = target;
            ConnectionString = connectionString;
        }

        public IDbConnection createConnection()
        {
            AuthenticationContext authenticationContext = new AuthenticationContext(Authority);
            AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(Target, ClientCredential).Result;
            SqlConnection WorkspaceDataConnection = new SqlConnection(ConnectionString);
            WorkspaceDataConnection.AccessToken = authenticationResult.AccessToken;

            return WorkspaceDataConnection;
        }
    }
}

After successful connection and a few queries, I get the following exception:

System.Data.SqlClient.SqlException (0x80131904): Resource ID : 1. The request limit for the database is 90 and has been reached. See 'http://go.microsoft.com/fwlink/?LinkId=267637' for assistance.

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) at LinqToDB.Data.DataConnection.ExecuteReader(CommandBehavior commandBehavior) in C:\projects\linq2db\Source\LinqToDB\Data\DataConnection.cs:line 1227 at LinqToDB.Linq.QueryRunner.ExecuteQuery[T](Query query, IDataContext dataContext, Mapper
1 mapper, Expression expression, Object[] ps, Int32 queryNumber)+MoveNext() in C:\projects\linq2db\Source\LinqToDB\Linq\QueryRunner.cs:line 320 at LinqToDB.Linq.Builder.TableBuilder.AssociatedTableContext.SubQueryHelper1.ExecuteSubQuery(IQueryRunner queryRunner, Object parentObject, Func3 queryReader)+MoveNext() in C:\projects\linq2db\Source\LinqToDB\Linq\Builder\TableBuilder.AssociatedTableContext.cs:line 460 at System.Collections.Generic.List1.AddEnumerable(IEnumerable1 enumerable) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at lambda_method(Closure , IQueryRunner , IDataReader ) at LinqToDB.Linq.QueryRunner.Mapper1.Map(IQueryRunner queryRunner, IDataReader dataReader) in C:\projects\linq2db\Source\LinqToDB\Linq\QueryRunner.cs:line 56 at LinqToDB.Linq.QueryRunner.ExecuteQuery[T](Query query, IDataContext dataContext, Mapper1 mapper, Expression expression, Object[] ps, Int32 queryNumber)+MoveNext() in C:\projects\linq2db\Source\LinqToDB\Linq\QueryRunner.cs:line 324 at System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext() at System.Linq.Enumerable.UnionIterator1.MoveNext() at System.Linq.Enumerable.SelectEnumerableIterator2.MoveNext() at System.Linq.Set1.UnionWith(IEnumerable1 other) at System.Linq.Enumerable.DistinctIterator1.FillSet() at System.Linq.Enumerable.DistinctIterator1.ToArray()

......................... at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at System.Threading.Tasks.ValueTask`1.get_Result() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext) at Workspace.API.Middlewares.AddUserHeadersMiddleware.InvokeAsync(HttpContext context, IWorkspaceRepository workspaceRepository) in C:\TFS\AT_NCSWorkspace\WorkSpaceAPI\src\API\Middlewares\AddUserHeadersMiddleware.cs:line 47 at Workspace.API.Middlewares.ErrorLoggingMiddleware.InvokeAsync(HttpContext context) in C:\TFS\AT_NCSWorkspace\WorkSpaceAPI\src\API\Middlewares\ErrorLoggingMiddleware.cs:line 31 ClientConnectionId:3c0ec020-5be1-4bda-adc1-205038682b08```

Steps to reproduce

Include a complete code listing (or project/solution) that we can run to reproduce the issue.

Partial code listings, or multiple fragments of code, will slow down our response or cause us to push the issue back to you to provide code to reproduce the issue.

<code with error and mapping classes>

Environment details

  • linq2db version: 2.6.4 with System.Data.SqlClient 4.6.1
  • Database Server: Azure SqlServer
  • Database Provider: SqlServer
  • Operating system: Windows
  • .NET Framework: .net Core 2.2
c#
asp.net-core
azure-sql-database
dbconnectionfactory
asked on Stack Overflow Aug 8, 2019 by Tauqir • edited Aug 9, 2019 by marc_s

1 Answer

-1

Changed the factory to static. This solved the too many connections problem.

answered on Stack Overflow Aug 11, 2019 by Tauqir

User contributions licensed under CC BY-SA 3.0