AddPortalDbContext.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using EVCB_OCPP.Domain;
  2. using EVCB_OCPP.Domain.Extensions;
  3. using Microsoft.Data.SqlClient;
  4. using Microsoft.EntityFrameworkCore;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.Logging;
  8. using NLog.Extensions.Logging;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Configuration;
  12. using System.Data.Entity.Infrastructure;
  13. using System.Diagnostics;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. namespace EVCB_OCPP.WSServer.Helper;
  18. public static class AddPortalDbContext
  19. {
  20. public const string CommandTimeoutKey = "CommandTimeout";
  21. public static IServiceCollection AddWebDBConetext(this IServiceCollection services, IConfiguration configuration)
  22. {
  23. const string DbUserIdKey = "WebDbUserId";
  24. const string DbPassKey = "WebDbPass";
  25. const string DbConnectionStringKey = "WebDBContext";
  26. var conneciotnString = configuration.GetConnectionString(DbUserIdKey, DbPassKey, DbConnectionStringKey);
  27. services.AddSqlConnectionFactory<WebDBConetext>(conneciotnString);
  28. return services;
  29. }
  30. public static IServiceCollection AddOnlineLogDBContext(this IServiceCollection services, IConfiguration configuration)
  31. {
  32. const string DbUserIdKey = "OnlineLogDbUserId";
  33. const string DbPassKey = "OnlineLogDbPass";
  34. const string DbConnectionStringKey = "OnlineLogDBContext";
  35. var conneciotnString = configuration.GetConnectionString(DbUserIdKey, DbPassKey, DbConnectionStringKey);
  36. services.AddSqlConnectionFactory<OnlineLogDBContext>(conneciotnString);
  37. return services;
  38. }
  39. private static void AddPortalDbContextInternal<T>(
  40. IServiceCollection services, IConfiguration configuration,
  41. string connectionString,bool logToConsole = false) where T : DbContext
  42. {
  43. var commandTimeout = int.TryParse(configuration[CommandTimeoutKey], out var temp) ? temp : 180;
  44. services.AddPooledDbContextFactory<T>((serviceProvider, options) => {
  45. options.UseSqlServer(connectionString, dbOptions =>
  46. {
  47. dbOptions.CommandTimeout(commandTimeout);
  48. });
  49. options.UseLoggerFactory(serviceProvider.GetRequiredService<ILoggerFactory>());
  50. });
  51. }
  52. }
  53. /// <summary>
  54. /// Dummy
  55. /// </summary>
  56. public class WebDBConetext : DbContext {}
  57. /// <summary>
  58. /// Dummy
  59. /// </summary>
  60. public class OnlineLogDBContext : DbContext { }