Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ConnectionUtil.cs 1.6 KiB

pirms 7 gadiem
pirms 7 gadiem
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using Npgsql;
  3. namespace DotNetCore.CAP.PostgreSql.Test
  4. {
  5. public static class ConnectionUtil
  6. {
  7. private const string DatabaseVariable = "Cap_PostgreSql_DatabaseName";
  8. private const string ConnectionStringTemplateVariable = "Cap_PostgreSql_ConnectionStringTemplate";
  9. private const string MasterDatabaseName = "postgres";
  10. private const string DefaultDatabaseName = @"DotNetCore.CAP.PostgreSql.Test";
  11. private const string DefaultConnectionStringTemplate =
  12. @"Server=localhost;Database={0};UserId=postgres;Password=123123;";
  13. public static string GetDatabaseName()
  14. {
  15. return Environment.GetEnvironmentVariable(DatabaseVariable) ?? DefaultDatabaseName;
  16. }
  17. public static string GetMasterConnectionString()
  18. {
  19. return string.Format(GetConnectionStringTemplate(), MasterDatabaseName);
  20. }
  21. public static string GetConnectionString()
  22. {
  23. return string.Format(GetConnectionStringTemplate(), GetDatabaseName());
  24. }
  25. private static string GetConnectionStringTemplate()
  26. {
  27. return
  28. Environment.GetEnvironmentVariable(ConnectionStringTemplateVariable) ??
  29. DefaultConnectionStringTemplate;
  30. }
  31. public static NpgsqlConnection CreateConnection(string connectionString = null)
  32. {
  33. connectionString = connectionString ?? GetConnectionString();
  34. var connection = new NpgsqlConnection(connectionString);
  35. connection.Open();
  36. return connection;
  37. }
  38. }
  39. }