From 223c7b0434327cc51921c41b7e78eedf6720c7e5 Mon Sep 17 00:00:00 2001 From: Mikhail Trubnikov Date: Tue, 19 Sep 2023 14:34:55 +1000 Subject: [PATCH] db configuration provider --- PARR.API/Controllers/V1/TemplateController.cs | 5 ++- PARR.API/Program.cs | 4 ++ .../DbSettings/DBConfigurationExtantions.cs | 13 ++++++ .../DbSettings/DBConfigurationProvider.cs | 42 +++++++++++++++++++ .../DbSettings/DBConfigurationSource.cs | 20 +++++++++ PARR.DAL/Context/DataContext.cs | 7 ++-- PARR.DAL/Contracts/SettingsEnum.cs | 9 ---- PARR.DAL/Contracts/SettingsFromDb.cs | 26 ++++++++++++ PARR.DAL/Contracts/SettingsTypesEnum.cs | 10 ----- ... 20230919043205_TblTemplWorks.Designer.cs} | 11 +---- ...rks.cs => 20230919043205_TblTemplWorks.cs} | 13 +++--- .../Migrations/DataContextModelSnapshot.cs | 9 +--- PARR.DAL/Models/Setting.cs | 7 +--- PARR.DAL/PARR.DAL.csproj | 1 + PARR.DAL/ParrDalInstaller.cs | 38 ++++++++++++++++- 15 files changed, 162 insertions(+), 53 deletions(-) create mode 100644 PARR.DAL/Configurations/DbSettings/DBConfigurationExtantions.cs create mode 100644 PARR.DAL/Configurations/DbSettings/DBConfigurationProvider.cs create mode 100644 PARR.DAL/Configurations/DbSettings/DBConfigurationSource.cs delete mode 100644 PARR.DAL/Contracts/SettingsEnum.cs create mode 100644 PARR.DAL/Contracts/SettingsFromDb.cs delete mode 100644 PARR.DAL/Contracts/SettingsTypesEnum.cs rename PARR.DAL/Migrations/{20230919020903_TblTemplWorks.Designer.cs => 20230919043205_TblTemplWorks.Designer.cs} (99%) rename PARR.DAL/Migrations/{20230919020903_TblTemplWorks.cs => 20230919043205_TblTemplWorks.cs} (95%) diff --git a/PARR.API/Controllers/V1/TemplateController.cs b/PARR.API/Controllers/V1/TemplateController.cs index 459d6ff9..20286cc5 100644 --- a/PARR.API/Controllers/V1/TemplateController.cs +++ b/PARR.API/Controllers/V1/TemplateController.cs @@ -18,14 +18,17 @@ namespace PARR.API.Controllers.V1 { private readonly IMapper mapper; private readonly ITemplateService templateService; + private readonly SettingsFromDb settingsFromDb; public TemplateController( IMapper mapper, - ITemplateService templateService + ITemplateService templateService, + SettingsFromDb settingsFromDb ) { this.mapper = mapper; this.templateService = templateService; + this.settingsFromDb = settingsFromDb; } diff --git a/PARR.API/Program.cs b/PARR.API/Program.cs index 37d07585..8f526c47 100644 --- a/PARR.API/Program.cs +++ b/PARR.API/Program.cs @@ -21,6 +21,10 @@ builder.Services.InstallApiServices(builder.Configuration); builder.Services.InstallSettings(builder.Configuration); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); +// Dal configuration +builder.Configuration.AddDalConfigurations(builder.Services); +builder.Services.AddDallSettings(builder.Configuration); + builder.Services.AddHttpContextAccessor(); builder.Services.AddControllers(); diff --git a/PARR.DAL/Configurations/DbSettings/DBConfigurationExtantions.cs b/PARR.DAL/Configurations/DbSettings/DBConfigurationExtantions.cs new file mode 100644 index 00000000..c3167e01 --- /dev/null +++ b/PARR.DAL/Configurations/DbSettings/DBConfigurationExtantions.cs @@ -0,0 +1,13 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace PARR.DAL.Configurations.DbSettings +{ + internal static class DBConfigurationExtantions + { + public static IConfigurationBuilder AddDbSettings(this IConfigurationBuilder builder, IServiceCollection services) + { + return builder.Add(new DBConfigurationSource(services)); + } + } +} diff --git a/PARR.DAL/Configurations/DbSettings/DBConfigurationProvider.cs b/PARR.DAL/Configurations/DbSettings/DBConfigurationProvider.cs new file mode 100644 index 00000000..1c542296 --- /dev/null +++ b/PARR.DAL/Configurations/DbSettings/DBConfigurationProvider.cs @@ -0,0 +1,42 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using PARR.DAL.Context; +using PARR.DAL.Contracts; + +namespace PARR.DAL.Configurations.DbSettings +{ + internal class DBConfigurationProvider : ConfigurationProvider + { + private readonly IServiceCollection services; + + public DBConfigurationProvider(IServiceCollection services) + { + this.services = services; + } + + public override void Load() + { + using (var dataContext = services.BuildServiceProvider().GetService()) + { + //если миграциями БД еще не создана, то SettingsInDbs будет недоступна + try + { + var settings = dataContext?.Setting.ToList(); + + if (settings == null) + return; + + if (settings != null) + { + //формируем список с корневым SettingsFromDb, и в него вложены дочерние настройки из БД, чтобы потом забиндить в класс + Data = settings.ToDictionary(settings => $"{nameof(SettingsFromDb)}:{settings.Name}", settings => (string?)settings.Value); + } + } + catch (Exception ex) + { + //TODO: логи, я не тестил, возможно надо через BuildServiceProvider прокинуть ILogger + } + } + } + } +} diff --git a/PARR.DAL/Configurations/DbSettings/DBConfigurationSource.cs b/PARR.DAL/Configurations/DbSettings/DBConfigurationSource.cs new file mode 100644 index 00000000..4b8d98cf --- /dev/null +++ b/PARR.DAL/Configurations/DbSettings/DBConfigurationSource.cs @@ -0,0 +1,20 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace PARR.DAL.Configurations.DbSettings +{ + internal class DBConfigurationSource : IConfigurationSource + { + private readonly IServiceCollection services; + + public DBConfigurationSource(IServiceCollection services) + { + this.services = services; + } + + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new DBConfigurationProvider(services); + } + } +} diff --git a/PARR.DAL/Context/DataContext.cs b/PARR.DAL/Context/DataContext.cs index 3e8ed53a..38dbe441 100644 --- a/PARR.DAL/Context/DataContext.cs +++ b/PARR.DAL/Context/DataContext.cs @@ -99,10 +99,11 @@ namespace PARR.DAL.Context modelBuilder.Entity(f => { + // При добавлении записей, добавлять тоже в PARR.DAL.Contracts.SettingsFromDb f.HasData( - new { Name = SettingsEnum.Initiator.ToString(), Description = "Инициатор регламентной работы, указывается при создании шаблона в ЕСПП.", Type = SettingsTypesEnum.String.ToString(), Value = "" }, - new { Name = SettingsEnum.ClosingCode.ToString(), Description = "Код закрытия регламентной работы, указывается при создании шаблона в ЕСПП.", Type = SettingsTypesEnum.String.ToString(), Value = "выполнен" }, - new { Name = SettingsEnum.Category.ToString(), Description = "Категория создаваемого объекта в ЕСПП", Type = SettingsTypesEnum.String.ToString(), Value = "регламентная работа" } + new { Name = nameof(SettingsFromDb.Initiator), Description = "Инициатор регламентной работы, указывается при создании шаблона в ЕСПП.", Value = "КУЗНЕЦОВ МИХАИЛ ВАЛЕРЬЕВИЧ (IVC_KUZNETSOVMV@DVGD.OAO.RZD)" }, + new { Name = nameof(SettingsFromDb.ClosingCode), Description = "Код закрытия регламентной работы, указывается при создании шаблона в ЕСПП.", Value = "выполнен" }, + new { Name = nameof(SettingsFromDb.Category), Description = "Категория создаваемого объекта в ЕСПП", Value = "регламентная работа" } ); }); diff --git a/PARR.DAL/Contracts/SettingsEnum.cs b/PARR.DAL/Contracts/SettingsEnum.cs deleted file mode 100644 index 0e44004b..00000000 --- a/PARR.DAL/Contracts/SettingsEnum.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace PARR.DAL.Contracts -{ - public enum SettingsEnum - { - Initiator, - ClosingCode, - Category - } -} \ No newline at end of file diff --git a/PARR.DAL/Contracts/SettingsFromDb.cs b/PARR.DAL/Contracts/SettingsFromDb.cs new file mode 100644 index 00000000..7c906c34 --- /dev/null +++ b/PARR.DAL/Contracts/SettingsFromDb.cs @@ -0,0 +1,26 @@ +namespace PARR.DAL.Contracts +{ + /// + /// Настройки из БД + /// + public class SettingsFromDb + { + // При добавлении свойств, добавлять в миграцию: PARR.DAL.Context.DataContext + + + /// + /// Инициатор регламентной работы, указывается при создании шаблона в ЕСПП. + /// + public string Initiator { get; set; } = string.Empty; + + /// + /// Код закрытия регламентной работы, указывается при создании шаблона в ЕСПП. + /// + public string ClosingCode { get; set; } = string.Empty; + + /// + /// Категория создаваемого объекта в ЕСПП + /// + public string Category { get; set; } = string.Empty; + } +} diff --git a/PARR.DAL/Contracts/SettingsTypesEnum.cs b/PARR.DAL/Contracts/SettingsTypesEnum.cs deleted file mode 100644 index 45f73e21..00000000 --- a/PARR.DAL/Contracts/SettingsTypesEnum.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace PARR.DAL.Contracts -{ - public enum SettingsTypesEnum - { - Int, - Decimal, - String, - Bool - } -} diff --git a/PARR.DAL/Migrations/20230919020903_TblTemplWorks.Designer.cs b/PARR.DAL/Migrations/20230919043205_TblTemplWorks.Designer.cs similarity index 99% rename from PARR.DAL/Migrations/20230919020903_TblTemplWorks.Designer.cs rename to PARR.DAL/Migrations/20230919043205_TblTemplWorks.Designer.cs index 8ec698d8..5deb1475 100644 --- a/PARR.DAL/Migrations/20230919020903_TblTemplWorks.Designer.cs +++ b/PARR.DAL/Migrations/20230919043205_TblTemplWorks.Designer.cs @@ -12,7 +12,7 @@ using PARR.DAL.Context; namespace PARR.DAL.Migrations { [DbContext(typeof(DataContext))] - [Migration("20230919020903_TblTemplWorks")] + [Migration("20230919043205_TblTemplWorks")] partial class TblTemplWorks { /// @@ -445,10 +445,6 @@ namespace PARR.DAL.Migrations .IsRequired() .HasColumnType("text"); - b.Property("Type") - .IsRequired() - .HasColumnType("text"); - b.Property("Value") .IsRequired() .HasColumnType("text"); @@ -462,21 +458,18 @@ namespace PARR.DAL.Migrations { Name = "Initiator", Description = "Инициатор регламентной работы, указывается при создании шаблона в ЕСПП.", - Type = "String", - Value = "" + Value = "КУЗНЕЦОВ МИХАИЛ ВАЛЕРЬЕВИЧ (IVC_KUZNETSOVMV@DVGD.OAO.RZD)" }, new { Name = "ClosingCode", Description = "Код закрытия регламентной работы, указывается при создании шаблона в ЕСПП.", - Type = "String", Value = "выполнен" }, new { Name = "Category", Description = "Категория создаваемого объекта в ЕСПП", - Type = "String", Value = "регламентная работа" }); }); diff --git a/PARR.DAL/Migrations/20230919020903_TblTemplWorks.cs b/PARR.DAL/Migrations/20230919043205_TblTemplWorks.cs similarity index 95% rename from PARR.DAL/Migrations/20230919020903_TblTemplWorks.cs rename to PARR.DAL/Migrations/20230919043205_TblTemplWorks.cs index caaa83ce..8e0753f8 100644 --- a/PARR.DAL/Migrations/20230919020903_TblTemplWorks.cs +++ b/PARR.DAL/Migrations/20230919043205_TblTemplWorks.cs @@ -117,9 +117,8 @@ namespace PARR.DAL.Migrations columns: table => new { Name = table.Column(type: "text", nullable: false), - Description = table.Column(type: "text", nullable: false), - Type = table.Column(type: "text", nullable: false), - Value = table.Column(type: "text", nullable: false) + Value = table.Column(type: "text", nullable: false), + Description = table.Column(type: "text", nullable: false) }, constraints: table => { @@ -128,12 +127,12 @@ namespace PARR.DAL.Migrations migrationBuilder.InsertData( table: "Setting", - columns: new[] { "Name", "Description", "Type", "Value" }, + columns: new[] { "Name", "Description", "Value" }, values: new object[,] { - { "Category", "Категория создаваемого объекта в ЕСПП", "String", "регламентная работа" }, - { "ClosingCode", "Код закрытия регламентной работы, указывается при создании шаблона в ЕСПП.", "String", "выполнен" }, - { "Initiator", "Инициатор регламентной работы, указывается при создании шаблона в ЕСПП.", "String", "" } + { "Category", "Категория создаваемого объекта в ЕСПП", "регламентная работа" }, + { "ClosingCode", "Код закрытия регламентной работы, указывается при создании шаблона в ЕСПП.", "выполнен" }, + { "Initiator", "Инициатор регламентной работы, указывается при создании шаблона в ЕСПП.", "КУЗНЕЦОВ МИХАИЛ ВАЛЕРЬЕВИЧ (IVC_KUZNETSOVMV@DVGD.OAO.RZD)" } }); } diff --git a/PARR.DAL/Migrations/DataContextModelSnapshot.cs b/PARR.DAL/Migrations/DataContextModelSnapshot.cs index 3484bc93..9536747d 100644 --- a/PARR.DAL/Migrations/DataContextModelSnapshot.cs +++ b/PARR.DAL/Migrations/DataContextModelSnapshot.cs @@ -442,10 +442,6 @@ namespace PARR.DAL.Migrations .IsRequired() .HasColumnType("text"); - b.Property("Type") - .IsRequired() - .HasColumnType("text"); - b.Property("Value") .IsRequired() .HasColumnType("text"); @@ -459,21 +455,18 @@ namespace PARR.DAL.Migrations { Name = "Initiator", Description = "Инициатор регламентной работы, указывается при создании шаблона в ЕСПП.", - Type = "String", - Value = "" + Value = "КУЗНЕЦОВ МИХАИЛ ВАЛЕРЬЕВИЧ (IVC_KUZNETSOVMV@DVGD.OAO.RZD)" }, new { Name = "ClosingCode", Description = "Код закрытия регламентной работы, указывается при создании шаблона в ЕСПП.", - Type = "String", Value = "выполнен" }, new { Name = "Category", Description = "Категория создаваемого объекта в ЕСПП", - Type = "String", Value = "регламентная работа" }); }); diff --git a/PARR.DAL/Models/Setting.cs b/PARR.DAL/Models/Setting.cs index f9dc3ed7..2745e5e5 100644 --- a/PARR.DAL/Models/Setting.cs +++ b/PARR.DAL/Models/Setting.cs @@ -9,11 +9,8 @@ namespace PARR.DAL.Models [Key] public required string Name { get; set; } - public required string Description { get; set; } - - //SettingsTypesEnum - public required string Type { get; set; } - public required string Value { get; set; } + + public required string Description { get; set; } } } diff --git a/PARR.DAL/PARR.DAL.csproj b/PARR.DAL/PARR.DAL.csproj index 92142b15..5f116215 100644 --- a/PARR.DAL/PARR.DAL.csproj +++ b/PARR.DAL/PARR.DAL.csproj @@ -12,6 +12,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/PARR.DAL/ParrDalInstaller.cs b/PARR.DAL/ParrDalInstaller.cs index d22dc4e4..e160a6e2 100644 --- a/PARR.DAL/ParrDalInstaller.cs +++ b/PARR.DAL/ParrDalInstaller.cs @@ -1,7 +1,9 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using PARR.DAL.Configurations.DbSettings; using PARR.DAL.Context; +using PARR.DAL.Contracts; using PARR.DAL.Services; using PARR.DAL.Services.Implementation; using PARR.DAL.Services.Implementations; @@ -15,11 +17,16 @@ namespace PARR.DAL { public static class ParrDalInstaller { + /// + /// Устанавливает Dal сервисы (1) + /// + /// + /// public static void InstallDalServices(this IServiceCollection services, IConfiguration configuration) { services.AddDbContext(opt => opt.UseNpgsql(configuration.GetConnectionString("DefaultConnection")) - ); + ); services.AddTransient(); services.AddTransient(); @@ -36,5 +43,34 @@ namespace PARR.DAL services.AddTransient(); services.AddTransient(); } + + /// + /// Добавляет конфигурацию Dal (2) + /// + /// + /// + /// + public static IConfigurationBuilder AddDalConfigurations(this IConfigurationBuilder builder, IServiceCollection services) + { + builder.Add(new DBConfigurationSource(services)); + + return builder; + } + + /// + /// Добавляет конфигурацию в сервисы (3) + /// + /// + /// + public static void AddDallSettings(this IServiceCollection services, IConfiguration configuration) + { + //SettingsFromDb configuration + var settingsFromDb = new SettingsFromDb(); + configuration.GetSection(nameof(SettingsFromDb)).Bind(settingsFromDb); + services.AddSingleton(settingsFromDb); + } + + + } }