I'm trying to connect to Oracle through .NET Core following this docs:
But I'm facing this error:
This property cannot be set after a connection has been opened System.InvalidOperationException: This property cannot be set after a connection has been opened at Oracle.ManagedDataAccess.Client.OracleDataSourceCollection.Add(String tnsName, String tnsDescriptor) at Infrastructure.Persistence.Factory.ConnectionFactory.SetupOracleConnection() in C:\Users\WINDOWS\RiderProjects\TicketsAPI\Infrastructure\Persistence\Factory\ConnectionFactory.cs:line 22
I don't have clue why this is happening, there's my ConnectionFactory:
using System.Data;
using Microsoft.Extensions.Logging;
using Oracle.ManagedDataAccess.Client;
namespace Infrastructure.Persistence.Factory;
public class ConnectionFactory : IConnectionFactory
{
private const string TnsName = "ORCL";
private readonly ILogger<ConnectionFactory> _logger;
public ConnectionFactory(ILogger<ConnectionFactory> logger)
{
_logger = logger;
}
public IDbConnection? Connection => SetupOracleConnection();
private OracleConnection? SetupOracleConnection()
{
OracleConfiguration.OracleDataSources.Add(TnsName,
"(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = DESKTOP-FP8GDE4)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = orcl)))"); // <-- This is the line 22 mentioned in the StackTrace
. . . //Some configs that are in the doc file.
OracleConnection oracleConnection = null!;
try
{
oracleConnection = new OracleConnection($"user id=kevinadmin; password=1234; data source={TnsName}");
oracleConnection.Open();
return oracleConnection;
}
catch (Exception e)
{
_logger.LogError("An error occurred while trying to connect to database {EMessage}", e.Message);
return null;
}
finally
{
oracleConnection?.Close();
}
}
}
CodePudding user response:
[edit:
I may have misunderstood the issue. If the exception is happening on second and subsequent calls to Connection
, then this answer might apply]
By declaring your property like
public IDbConnection? Connection => SetupOracleConnection();
you're instructing the { get; }
(which is what the =>
is sugar for) to execute the SetupOracleConnection()
every time it is accessed.
You should try to encapsulate that into a singleton instance.
private IDbConnection? _connection = null;
public IDbConnection? Connection => _connection ?? ( _connection = SetupOracleConnection());