diff --git a/Client.Wasm/Client.Wasm.csproj b/Client.Wasm/Client.Wasm.csproj
index 0ba9f90..0c323bf 100644
--- a/Client.Wasm/Client.Wasm.csproj
+++ b/Client.Wasm/Client.Wasm.csproj
@@ -4,6 +4,7 @@
net8.0
enable
enable
+ Debug;Release;123
diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor
index 661f118..a53bf00 100644
--- a/Client.Wasm/Components/StudentCard.razor
+++ b/Client.Wasm/Components/StudentCard.razor
@@ -4,10 +4,12 @@
- Номер №X "Название лабораторной"
- Вариант №Х "Название варианта"
- Выполнена Фамилией Именем 65ХХ
- Ссылка на форк
+ Номер №1 "Кэширование"
+
+ Вариант №8 "Сотрудник компании"
+
+ Выполнена Земляновым Владимиром 6511
+ Ссылка на форк
diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json
index 0d824ea..6ad691a 100644
--- a/Client.Wasm/Properties/launchSettings.json
+++ b/Client.Wasm/Properties/launchSettings.json
@@ -12,9 +12,9 @@
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
- "launchBrowser": true,
+ "launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
- "applicationUrl": "http://localhost:5127",
+ "applicationUrl": "http://localhost:5128",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@@ -22,20 +22,20 @@
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
- "launchBrowser": true,
+ "launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
- "applicationUrl": "https://localhost:7282;http://localhost:5127",
+ "applicationUrl": "https://localhost:7283;http://localhost:5128",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
- "launchBrowser": true,
+ "launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
-}
+}
\ No newline at end of file
diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json
index d1fe7ab..fcd8f03 100644
--- a/Client.Wasm/wwwroot/appsettings.json
+++ b/Client.Wasm/wwwroot/appsettings.json
@@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
- "BaseAddress": ""
-}
+ "BaseAddress": "https://localhost:7171/employee"
+}
\ No newline at end of file
diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln
index cb48241..ec784b5 100644
--- a/CloudDevelopment.sln
+++ b/CloudDevelopment.sln
@@ -5,16 +5,43 @@ VisualStudioVersion = 17.14.36811.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployees.AppHost", "CompanyEmployees.AppHost\CompanyEmployees.AppHost.csproj", "{96FC536F-9C20-45C4-B624-F3E2DEE96BA3}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployees.Generator", "CompanyEmployees.Generator\CompanyEmployees.Generator.csproj", "{418E6A76-7DE1-04F1-F18A-9A7C9ED44857}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyEmployees.ServiceDefaults", "CompanyEmployees.ServiceDefaults\CompanyEmployees.ServiceDefaults.csproj", "{53C4EDF4-E3C2-A484-171F-78A5FD7190F6}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ 123|Any CPU = 123|Any CPU
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {AE7EEA74-2FE0-136F-D797-854FD87E022A}.123|Any CPU.ActiveCfg = 123|Any CPU
+ {AE7EEA74-2FE0-136F-D797-854FD87E022A}.123|Any CPU.Build.0 = 123|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU
+ {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.123|Any CPU.ActiveCfg = 123|Any CPU
+ {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.123|Any CPU.Build.0 = 123|Any CPU
+ {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {96FC536F-9C20-45C4-B624-F3E2DEE96BA3}.Release|Any CPU.Build.0 = Release|Any CPU
+ {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.123|Any CPU.ActiveCfg = Release|Any CPU
+ {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.123|Any CPU.Build.0 = Release|Any CPU
+ {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {418E6A76-7DE1-04F1-F18A-9A7C9ED44857}.Release|Any CPU.Build.0 = Release|Any CPU
+ {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.123|Any CPU.ActiveCfg = 123|Any CPU
+ {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.123|Any CPU.Build.0 = 123|Any CPU
+ {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {53C4EDF4-E3C2-A484-171F-78A5FD7190F6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj b/CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj
new file mode 100644
index 0000000..dd87fa5
--- /dev/null
+++ b/CompanyEmployees.AppHost/CompanyEmployees.AppHost.csproj
@@ -0,0 +1,24 @@
+
+
+
+ net8.0
+ enable
+ enable
+ enable
+ true
+ Debug;Release;123
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CompanyEmployees.AppHost/Program.cs b/CompanyEmployees.AppHost/Program.cs
new file mode 100644
index 0000000..6e2759c
--- /dev/null
+++ b/CompanyEmployees.AppHost/Program.cs
@@ -0,0 +1,13 @@
+var builder = DistributedApplication.CreateBuilder(args);
+
+var redis = builder.AddRedis("redis")
+ .WithRedisCommander();
+
+var generator = builder.AddProject("generator")
+ .WithReference(redis)
+ .WithExternalHttpEndpoints();
+
+builder.AddProject("client")
+ .WithReference(generator);
+
+builder.Build().Run();
\ No newline at end of file
diff --git a/CompanyEmployees.AppHost/Properties/launchSettings.json b/CompanyEmployees.AppHost/Properties/launchSettings.json
new file mode 100644
index 0000000..09cd82d
--- /dev/null
+++ b/CompanyEmployees.AppHost/Properties/launchSettings.json
@@ -0,0 +1,29 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "profiles": {
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:17170;http://localhost:15170",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21170",
+ "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22170"
+ }
+ },
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:15170",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19170",
+ "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20170"
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/CompanyEmployees.AppHost/appsettings.Development.json b/CompanyEmployees.AppHost/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/CompanyEmployees.AppHost/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/CompanyEmployees.AppHost/appsettings.json b/CompanyEmployees.AppHost/appsettings.json
new file mode 100644
index 0000000..31c092a
--- /dev/null
+++ b/CompanyEmployees.AppHost/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Aspire.Hosting.Dcp": "Warning"
+ }
+ }
+}
diff --git a/CompanyEmployees.Generator/CompanyEmployees.Generator.csproj b/CompanyEmployees.Generator/CompanyEmployees.Generator.csproj
new file mode 100644
index 0000000..b0d3ba2
--- /dev/null
+++ b/CompanyEmployees.Generator/CompanyEmployees.Generator.csproj
@@ -0,0 +1,19 @@
+
+
+
+ net8.0
+ enable
+ enable
+ Debug;Release;123
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CompanyEmployees.Generator/Models/CompanyEmployee.cs b/CompanyEmployees.Generator/Models/CompanyEmployee.cs
new file mode 100644
index 0000000..8244082
--- /dev/null
+++ b/CompanyEmployees.Generator/Models/CompanyEmployee.cs
@@ -0,0 +1,64 @@
+namespace CompanyEmployees.Generator.Models;
+
+///
+/// Модель сотрудника компании
+///
+public class CompanyEmployeeModel
+{
+ ///
+ /// Идентификатор сотрудника в системе
+ ///
+ public int Id { get; set; }
+
+ ///
+ /// ФИО
+ ///
+ /// Конкатенация фамилии, имени и отчества через пробел
+ ///
+ ///
+ public required string FullName { get; set; }
+
+ ///
+ /// Должность
+ /// Выбирается из справочника профессий (“Developer”, “Manager”, “Analyst” и т.д.) и справочника суффиксов к ним (“Junior”, “Middle”, “Senior” и т.д.)
+ ///
+ public required string Position { get; set; }
+
+ ///
+ /// Отдел
+ ///
+ public required string Section { get; set; }
+
+ ///
+ /// Дата приема
+ /// Ограничение: не более 10 лет назад от текущей даты
+ ///
+ public required DateOnly AdmissionDate { get; set; }
+
+ ///
+ /// Оклад
+ /// Значение коррелирует с суффиксом должности
+ ///
+ public required decimal Salary { get; set; }
+
+ ///
+ /// Электронная почта
+ ///
+ public required string Email { get; set; }
+
+ ///
+ /// Номер телефона формата +7(***)***-**-**
+ ///
+ public required string PhoneNumber { get; set; }
+
+ ///
+ /// Индикатор увольнения
+ ///
+ public required bool Dismissal { get; set; } = false;
+
+ ///
+ /// Дата увольнения
+ /// При отсутствии индикатора увольнения дата увольнения не заполняется
+ ///
+ public DateOnly? DismissalDate { get; set; }
+}
diff --git a/CompanyEmployees.Generator/Program.cs b/CompanyEmployees.Generator/Program.cs
new file mode 100644
index 0000000..582edef
--- /dev/null
+++ b/CompanyEmployees.Generator/Program.cs
@@ -0,0 +1,58 @@
+using CompanyEmployees.Generator.Services;
+using CompanyEmployees.ServiceDefaults;
+using Serilog;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.AddServiceDefaults();
+
+builder.AddRedisDistributedCache("redis");
+
+builder.Services.AddSingleton();
+builder.Services.AddScoped();
+
+builder.Services.AddCors(options =>
+{
+ options.AddDefaultPolicy(policy =>
+ {
+ policy.AllowAnyOrigin()
+ .AllowAnyMethod()
+ .AllowAnyHeader();
+ });
+});
+
+var app = builder.Build();
+
+app.UseCors();
+app.UseSerilogRequestLogging();
+
+app.MapDefaultEndpoints();
+
+app.MapGet("/employee", async (
+ int id,
+ CompanyEmployeeService service,
+ ILogger logger,
+ CancellationToken cancellationToken) =>
+{
+ logger.LogInformation("Received request for company employee with ID: {Id}", id);
+
+ if (id <= 0)
+ {
+ logger.LogWarning("Received invalid ID: {Id}", id);
+ return Results.BadRequest(new { error = "ID must be a positive number" });
+ }
+
+ try
+ {
+ var application = await service.GetByIdAsync(id, cancellationToken);
+ return Results.Ok(application);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Error while getting company employee {Id}", id);
+ return Results.Problem("An error occurred while processing the request");
+ }
+})
+.WithName("GetCompanyEmployee");
+
+app.Run();
\ No newline at end of file
diff --git a/CompanyEmployees.Generator/Properties/launchSettings.json b/CompanyEmployees.Generator/Properties/launchSettings.json
new file mode 100644
index 0000000..ea1476c
--- /dev/null
+++ b/CompanyEmployees.Generator/Properties/launchSettings.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": false,
+ "applicationUrl": "http://localhost:5171",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": false,
+ "applicationUrl": "https://localhost:7171;http://localhost:5171",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/CompanyEmployees.Generator/Services/CompanyEmployeeGenerator.cs b/CompanyEmployees.Generator/Services/CompanyEmployeeGenerator.cs
new file mode 100644
index 0000000..2362b33
--- /dev/null
+++ b/CompanyEmployees.Generator/Services/CompanyEmployeeGenerator.cs
@@ -0,0 +1,117 @@
+using Bogus;
+using Bogus.DataSets;
+using CompanyEmployees.Generator.Models;
+
+namespace CompanyEmployees.Generator.Services;
+
+///
+/// Генератор сотрудника по идентификатору
+///
+/// Логгер
+public class CompanyEmployeeGenerator(ILogger logger)
+{
+ ///
+ /// Справочник профессий сотрудников
+ ///
+ private static readonly string[] _positionProfessions =
+ [
+ "Developer",
+ "Manager",
+ "Analyst",
+ "DevOps Engineer",
+ "QA Engineer",
+ "System Architect"
+ ];
+
+ ///
+ /// Справочник суффиксов для профессий
+ ///
+ private enum PositionSuffix
+ {
+ Junior = 0,
+ Middle = 1,
+ Senior = 2,
+ TeamLead = 3
+ };
+
+ ///
+ /// Словарь множителей на основе суффиксов профессий
+ ///
+ private static readonly Dictionary _positionSuffixSalaryMultipliers = new()
+ {
+ [PositionSuffix.Junior] = 1m,
+ [PositionSuffix.Middle] = 1.5m,
+ [PositionSuffix.Senior] = 2.1m,
+ [PositionSuffix.TeamLead] = 2.6m
+ };
+
+ private readonly ILogger _logger = logger;
+
+ ///
+ /// Функция для генерации сотрудника на основе параметра id
+ ///
+ /// Идентификатор сотрудника в системе
+ /// Сгенерированные данные о сотруднике
+ public CompanyEmployeeModel Generate(int id)
+ {
+ _logger.LogInformation("Start generating company employee application with ID: {Id}", id);
+
+ var faker = new Faker("ru")
+ .UseSeed(id)
+ .RuleFor(x => x.Id, _ => id)
+ .RuleFor(x => x.FullName, f => GenerateEmployeeFullName(f))
+ .RuleFor(x => x.Position, f => GenerateEmployeePosition(f))
+ .RuleFor(x => x.Section, f => f.Commerce.Department())
+ .RuleFor(x => x.AdmissionDate, f => f.Date.PastDateOnly(10))
+ .RuleFor(x => x.Salary, (f, x) => GenerateEmployeeSalary(f, x))
+ .RuleFor(x => x.Email, f => f.Internet.Email())
+ .RuleFor(x => x.PhoneNumber, f => f.Phone.PhoneNumber("+7(###)###-##-##"))
+ .RuleFor(x => x.Dismissal, f => f.Random.Bool())
+ .RuleFor(x => x.DismissalDate, (f, x) => GenerateEmployeeDismissalDate(f, x));
+
+ _logger.LogInformation("Finally generate employee with ID: {Id}", id);
+
+ return faker.Generate();
+ }
+
+ private static string GenerateEmployeeFullName(Faker faker)
+ {
+ var gender = faker.PickRandom(Enum.GetValues(typeof(Name.Gender)).Cast().ToArray());
+
+ var firstName = faker.Name.FirstName(gender);
+ var lastName = faker.Name.LastName(gender);
+ var patronymic = faker.Name.FirstName(gender) + (gender == Name.Gender.Male ? "еевич" : "еевна");
+
+ return string.Join(' ', firstName, lastName, patronymic);
+ }
+
+ private static string GenerateEmployeePosition(Faker faker)
+ {
+ return string.Join(' ', faker.PickRandom(_positionProfessions), faker.PickRandom());
+ }
+
+ private static decimal GenerateEmployeeSalary(Faker faker, CompanyEmployeeModel x)
+ {
+ var baseSalary = faker.Random.Decimal(100, 200);
+ var finalSalary = baseSalary;
+
+ foreach (var kvp in _positionSuffixSalaryMultipliers)
+ {
+ if (x.Position.Contains(kvp.Key.ToString()))
+ {
+ finalSalary = baseSalary * kvp.Value;
+ break;
+ }
+ }
+
+ return Math.Round(baseSalary, 2);
+ }
+
+ private static DateOnly? GenerateEmployeeDismissalDate(Faker faker, CompanyEmployeeModel x)
+ {
+
+ if (x.Dismissal) return null;
+
+ return faker.Date.BetweenDateOnly(x.AdmissionDate, DateOnly.FromDateTime(DateTime.UtcNow));
+ }
+}
diff --git a/CompanyEmployees.Generator/Services/CompanyEmployeeService.cs b/CompanyEmployees.Generator/Services/CompanyEmployeeService.cs
new file mode 100644
index 0000000..6be51c9
--- /dev/null
+++ b/CompanyEmployees.Generator/Services/CompanyEmployeeService.cs
@@ -0,0 +1,68 @@
+using CompanyEmployees.Generator.Models;
+using Microsoft.Extensions.Caching.Distributed;
+using System.Text.Json;
+
+namespace CompanyEmployees.Generator.Services;
+
+///
+/// Сервис для работы с сотрудниками компании
+/// Каждый сгенерированный сотрудник сохраняется в кэш, если ранее он небыл получен
+/// В ином случае значение берется из кэша
+///
+/// Генератор необходимый для создания сотрудника
+/// Кэш хранящий ранее сгенерированных сотрудников
+/// Логгер
+public class CompanyEmployeeService(
+ CompanyEmployeeGenerator generator,
+ IDistributedCache cache,
+ ILogger logger
+)
+{
+ private readonly CompanyEmployeeGenerator _generator = generator;
+ private readonly IDistributedCache _cache = cache;
+ private readonly ILogger _logger = logger;
+
+ private static readonly TimeSpan _cacheExpiration = TimeSpan.FromMinutes(5);
+ private const string CacheKeyPrefix = "company-employee:";
+
+ ///
+ /// Функция для генерации или взятия из кэша сотрудника по id
+ ///
+ /// Id сотрудника
+ /// Токен для отмены операции
+ ///
+ public async Task GetByIdAsync(int id, CancellationToken cancellationToken = default)
+ {
+ var cacheKey = $"{CacheKeyPrefix}{id}";
+
+ _logger.LogInformation("Request for credit application with ID: {Id}", id);
+
+ var cachedData = await _cache.GetStringAsync(cacheKey, cancellationToken);
+
+ if (!string.IsNullOrEmpty(cachedData))
+ {
+ _logger.LogInformation("Credit application {Id} found in cache", id);
+ var cachedApplication = JsonSerializer.Deserialize(cachedData);
+ return cachedApplication!;
+ }
+
+ _logger.LogInformation("Credit application {Id} not found in cache, generating new one", id);
+
+ var application = _generator.Generate(id);
+
+ var serializedData = JsonSerializer.Serialize(application);
+ var cacheOptions = new DistributedCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = _cacheExpiration
+ };
+
+ await _cache.SetStringAsync(cacheKey, serializedData, cacheOptions, cancellationToken);
+
+ _logger.LogInformation(
+ "Credit application {Id} saved to cache with TTL {CacheExpiration} minutes",
+ id,
+ _cacheExpiration.TotalMinutes);
+
+ return application;
+ }
+}
diff --git a/CompanyEmployees.Generator/appsettings.Development.json b/CompanyEmployees.Generator/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/CompanyEmployees.Generator/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/CompanyEmployees.Generator/appsettings.json b/CompanyEmployees.Generator/appsettings.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/CompanyEmployees.Generator/appsettings.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/CompanyEmployees.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj b/CompanyEmployees.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj
new file mode 100644
index 0000000..4e142da
--- /dev/null
+++ b/CompanyEmployees.ServiceDefaults/CompanyEmployees.ServiceDefaults.csproj
@@ -0,0 +1,28 @@
+
+
+
+ net8.0
+ enable
+ enable
+ true
+ Debug;Release;123
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CompanyEmployees.ServiceDefaults/Extensions.cs b/CompanyEmployees.ServiceDefaults/Extensions.cs
new file mode 100644
index 0000000..f1836a6
--- /dev/null
+++ b/CompanyEmployees.ServiceDefaults/Extensions.cs
@@ -0,0 +1,104 @@
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Diagnostics.HealthChecks;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Trace;
+using Serilog;
+
+namespace CompanyEmployees.ServiceDefaults;
+
+public static class Extensions
+{
+ public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder)
+ {
+ builder.ConfigureSerilog();
+ builder.ConfigureOpenTelemetry();
+ builder.AddDefaultHealthChecks();
+ builder.Services.AddServiceDiscovery();
+ builder.Services.ConfigureHttpClientDefaults(http =>
+ {
+ http.AddStandardResilienceHandler();
+ http.AddServiceDiscovery();
+ });
+
+ return builder;
+ }
+
+ public static IHostApplicationBuilder ConfigureSerilog(this IHostApplicationBuilder builder)
+ {
+ Log.Logger = new LoggerConfiguration()
+ .ReadFrom.Configuration(builder.Configuration)
+ .Enrich.FromLogContext()
+ .Enrich.WithEnvironmentName()
+ .Enrich.WithThreadId()
+ .Enrich.WithMachineName()
+ .WriteTo.Console(outputTemplate:
+ "[{Timestamp:HH:mm:ss} {Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}")
+ .CreateLogger();
+
+ builder.Services.AddSerilog();
+
+ return builder;
+ }
+
+ public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder)
+ {
+ builder.Logging.AddOpenTelemetry(logging =>
+ {
+ logging.IncludeFormattedMessage = true;
+ logging.IncludeScopes = true;
+ });
+
+ builder.Services.AddOpenTelemetry()
+ .WithMetrics(metrics =>
+ {
+ metrics.AddAspNetCoreInstrumentation()
+ .AddHttpClientInstrumentation()
+ .AddRuntimeInstrumentation();
+ })
+ .WithTracing(tracing =>
+ {
+ tracing.AddAspNetCoreInstrumentation()
+ .AddHttpClientInstrumentation();
+ });
+
+ builder.AddOpenTelemetryExporters();
+
+ return builder;
+ }
+
+ private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder)
+ {
+ var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
+
+ if (useOtlpExporter)
+ {
+ builder.Services.AddOpenTelemetry().UseOtlpExporter();
+ }
+
+ return builder;
+ }
+
+ public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder)
+ {
+ builder.Services.AddHealthChecks()
+ .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
+
+ return builder;
+ }
+
+ public static WebApplication MapDefaultEndpoints(this WebApplication app)
+ {
+ app.MapHealthChecks("/health");
+ app.MapHealthChecks("/alive", new HealthCheckOptions
+ {
+ Predicate = r => r.Tags.Contains("live")
+ });
+
+ return app;
+ }
+}
\ No newline at end of file