diff --git a/TaskHub/.gitattributes b/TaskHub/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/TaskHub/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/TaskHub/.gitignore b/TaskHub/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/TaskHub/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/TaskHub/Api/DependencyInjection/DisposedService.cs b/TaskHub/Api/DependencyInjection/DisposedService.cs new file mode 100644 index 0000000..01ae2b2 --- /dev/null +++ b/TaskHub/Api/DependencyInjection/DisposedService.cs @@ -0,0 +1,17 @@ +namespace Api.DependencyInjection; + +public abstract class DisposedService : IHasInstanceId, IDisposable +{ + public Guid InstanceId { get; } = Guid.NewGuid(); + protected abstract string ServiceName { get; } + + protected DisposedService() + { + Console.WriteLine($"[CREATE] {ServiceName}: {InstanceId}"); + } + + public void Dispose() + { + Console.WriteLine($"[DISPOSE] {ServiceName}: {InstanceId}"); + } +} \ No newline at end of file diff --git a/TaskHub/Api/DependencyInjection/IHasInstanceId.cs b/TaskHub/Api/DependencyInjection/IHasInstanceId.cs new file mode 100644 index 0000000..00c05e1 --- /dev/null +++ b/TaskHub/Api/DependencyInjection/IHasInstanceId.cs @@ -0,0 +1,6 @@ +namespace Api.DependencyInjection; + +public interface IHasInstanceId +{ + Guid InstanceId { get; } +} \ No newline at end of file diff --git a/TaskHub/Api/DependencyInjection/LifetimeServices.cs b/TaskHub/Api/DependencyInjection/LifetimeServices.cs new file mode 100644 index 0000000..d72d489 --- /dev/null +++ b/TaskHub/Api/DependencyInjection/LifetimeServices.cs @@ -0,0 +1,42 @@ +namespace Api.DependencyInjection; + +// Интерфейсы +public interface ISingletonService1 : IHasInstanceId { } +public interface ISingletonService2 : IHasInstanceId { } +public interface IScopedService1 : IHasInstanceId { } +public interface IScopedService2 : IHasInstanceId { } +public interface ITransientService1 : IHasInstanceId { } +public interface ITransientService2 : IHasInstanceId { } + +// Реализации Singleton +public class SingletonService1 : DisposedService, ISingletonService1 +{ + protected override string ServiceName => nameof(SingletonService1); +} + +public class SingletonService2 : DisposedService, ISingletonService2 +{ + protected override string ServiceName => nameof(SingletonService2); +} + +// Реализации Scoped +public class ScopedService1 : DisposedService, IScopedService1 +{ + protected override string ServiceName => nameof(ScopedService1); +} + +public class ScopedService2 : DisposedService, IScopedService2 +{ + protected override string ServiceName => nameof(ScopedService2); +} + +// Реализации Transient +public class TransientService1 : DisposedService, ITransientService1 +{ + protected override string ServiceName => nameof(TransientService1); +} + +public class TransientService2 : DisposedService, ITransientService2 +{ + protected override string ServiceName => nameof(TransientService2); +} \ No newline at end of file diff --git a/TaskHub/Api/DependencyInjection/ServiceProviderExtensions.cs b/TaskHub/Api/DependencyInjection/ServiceProviderExtensions.cs new file mode 100644 index 0000000..addba1c --- /dev/null +++ b/TaskHub/Api/DependencyInjection/ServiceProviderExtensions.cs @@ -0,0 +1,23 @@ +namespace Api.DependencyInjection; + +public static class ServiceProviderExtensions +{ + public static void DemonstrateServiceLifetime(this IServiceProvider serviceProvider, string serviceName) + where TService : class, IHasInstanceId + { + Console.WriteLine($"\nДемонстрация {serviceName}"); + + var first = serviceProvider.GetService(); + var second = serviceProvider.GetService(); + + if (first == null || second == null) + { + Console.WriteLine($"Не удалось получить сервис {serviceName}"); + return; + } + + Console.WriteLine($"Первый InstanceId: {first.InstanceId}"); + Console.WriteLine($"Второй InstanceId: {second.InstanceId}"); + Console.WriteLine($"Это один и тот же объект: {ReferenceEquals(first, second)}"); + } +} \ No newline at end of file diff --git a/TaskHub/Api/Middleware/ResponseTimeMiddleware.cs b/TaskHub/Api/Middleware/ResponseTimeMiddleware.cs new file mode 100644 index 0000000..24680cf --- /dev/null +++ b/TaskHub/Api/Middleware/ResponseTimeMiddleware.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; + +namespace Api.Middleware; + +/// +/// Middleware для измерения времени обработки HTTP запросов. +/// Добавляет заголовок X-Response-Time-Ms с временем выполнения запроса в миллисекундах. +/// +public class ResponseTimeMiddleware +{ + private readonly RequestDelegate _next; + + public ResponseTimeMiddleware(RequestDelegate next) + { + _next = next; + } + + /// + /// Обрабатывает HTTP запрос, измеряя время его выполнения. + /// + /// Контекст HTTP запроса + public async Task InvokeAsync(HttpContext context) + { + // Запускаем измерение времени + var stopwatch = Stopwatch.StartNew(); + + // Регистрируем callback, который добавит заголовок с временем ответа + context.Response.OnStarting(() => + { + stopwatch.Stop(); + context.Response.Headers["X-Response-Time-Ms"] = stopwatch.ElapsedMilliseconds.ToString(); + return Task.CompletedTask; + }); + + // Передаем управление следующему middleware в конвейере + await _next(context); + } +} \ No newline at end of file diff --git a/TaskHub/Api/Middleware/StudentInfoMiddleware.cs b/TaskHub/Api/Middleware/StudentInfoMiddleware.cs new file mode 100644 index 0000000..0b3d033 --- /dev/null +++ b/TaskHub/Api/Middleware/StudentInfoMiddleware.cs @@ -0,0 +1,33 @@ +namespace Api.Middleware; + +/// +/// Middleware для добавления информации о студенте в заголовки ответа +/// +public class StudentInfoMiddleware +{ + private readonly RequestDelegate _next; + + /// + /// Конструктор middleware + /// + /// Следующий middleware в конвейере + public StudentInfoMiddleware(RequestDelegate next) + { + _next = next; + } + + /// + /// Обработка HTTP-запроса + /// + /// HTTP контекст + public async Task InvokeAsync(HttpContext context) + { + context.Response.OnStarting(() => + { + context.Response.Headers["X-Student-Group"] = "RI-240947"; + context.Response.Headers["X-Student-Name"] = "Khaliullin Almaz Ildarovich"; + return Task.CompletedTask; + }); + await _next(context); + } +} \ No newline at end of file diff --git a/TaskHub/Api/Program.cs b/TaskHub/Api/Program.cs index 6c9086d..05c6ace 100644 --- a/TaskHub/Api/Program.cs +++ b/TaskHub/Api/Program.cs @@ -1,24 +1,63 @@ +using Api.DependencyInjection; using LoggingLibrary; namespace Api; -/// -/// Точка входа приложения -/// public sealed class Program { - /// - /// Запуск приложения - /// public static void Main(string[] args) { - Host.CreateDefaultBuilder(args) + Console.WriteLine("Жизненные циклы DI"); + + var host = Host.CreateDefaultBuilder(args) .UseInfraSerilog() .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }) - .Build() - .Run(); + .Build(); + + var serviceProvider = host.Services; + + + Console.WriteLine("\nСоздание Singleton сервисов"); + using (var tempScope = serviceProvider.CreateScope()) + { + // Резолвим Singleton для создания + tempScope.ServiceProvider.GetService(); + tempScope.ServiceProvider.GetService(); + } + + + Console.WriteLine("\nПервый scope"); + using (var scope1 = serviceProvider.CreateScope()) + { + DemonstrateAllServices(scope1.ServiceProvider, "первом scope"); + } + + Console.WriteLine("\nВторой scope"); + using (var scope2 = serviceProvider.CreateScope()) + { + DemonstrateAllServices(scope2.ServiceProvider, "втором scope"); + } + + host.Run(); + } + + private static void DemonstrateAllServices(IServiceProvider serviceProvider, string scopeName) + { + Console.WriteLine($"\nДемонстрация в {scopeName}:"); + + + serviceProvider.DemonstrateServiceLifetime("SingletonService1"); + serviceProvider.DemonstrateServiceLifetime("SingletonService2"); + + + serviceProvider.DemonstrateServiceLifetime("ScopedService1"); + serviceProvider.DemonstrateServiceLifetime("ScopedService2"); + + + serviceProvider.DemonstrateServiceLifetime("TransientService1"); + serviceProvider.DemonstrateServiceLifetime("TransientService2"); } } \ No newline at end of file diff --git a/TaskHub/Api/StartUp.cs b/TaskHub/Api/StartUp.cs index 9220ca4..a940ce0 100644 --- a/TaskHub/Api/StartUp.cs +++ b/TaskHub/Api/StartUp.cs @@ -1,3 +1,5 @@ +using Api.DependencyInjection; +using Api.Middleware; using Api.UseCases.Users; using Api.UseCases.Users.Interfaces; using Dal; @@ -61,6 +63,15 @@ public void ConfigureServices(IServiceCollection services) Version = "v1" }); }); + + services.AddSingleton(); + services.AddSingleton(); + + services.AddScoped(); + services.AddScoped(); + + services.AddTransient(); + services.AddTransient(); } /// @@ -81,6 +92,9 @@ public void Configure(IApplicationBuilder app) app.UseRouting(); + app.UseMiddleware(); + app.UseMiddleware(); + app.UseEndpoints(endpoints => { endpoints.MapControllers(); diff --git a/TaskHub/Dal/Migrations/20260311124204_CreateUsers.Designer.cs b/TaskHub/Dal/Migrations/20260311124204_CreateUsers.Designer.cs new file mode 100644 index 0000000..63f758b --- /dev/null +++ b/TaskHub/Dal/Migrations/20260311124204_CreateUsers.Designer.cs @@ -0,0 +1,50 @@ +// +using System; +using Dal.Context; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Dal.Migrations +{ + [DbContext(typeof(UserDbContext))] + [Migration("20260311124204_CreateUsers")] + partial class CreateUsers + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Dal.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("LastActivityUtc") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_activity_utc"); + + b.Property("Name") + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("users", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/TaskHub/Dal/Migrations/20260311124204_CreateUsers.cs b/TaskHub/Dal/Migrations/20260311124204_CreateUsers.cs new file mode 100644 index 0000000..10c712a --- /dev/null +++ b/TaskHub/Dal/Migrations/20260311124204_CreateUsers.cs @@ -0,0 +1,35 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Dal.Migrations +{ + /// + public partial class CreateUsers : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "users", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + name = table.Column(type: "character varying(200)", maxLength: 200, nullable: true), + last_activity_utc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_users", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "users"); + } + } +} diff --git a/TaskHub/Dal/Migrations/UserDbContextModelSnapshot.cs b/TaskHub/Dal/Migrations/UserDbContextModelSnapshot.cs new file mode 100644 index 0000000..19485c0 --- /dev/null +++ b/TaskHub/Dal/Migrations/UserDbContextModelSnapshot.cs @@ -0,0 +1,47 @@ +// +using System; +using Dal.Context; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Dal.Migrations +{ + [DbContext(typeof(UserDbContext))] + partial class UserDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Dal.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("LastActivityUtc") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_activity_utc"); + + b.Property("Name") + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("users", (string)null); + }); +#pragma warning restore 612, 618 + } + } +}