Новая фабрика клиентов #17

Merged
on.nemtina merged 7 commits from feature/add-refit-factory into master 2025-01-10 13:54:19 +05:00
33 changed files with 448 additions and 451 deletions

View File

@ -16,12 +16,6 @@ namespace DD.Persistence.API;
public static class DependencyInjection public static class DependencyInjection
{ {
//public static void MapsterSetup()
//{
// TypeAdapterConfig.GlobalSettings.Default.Config
// .ForType<TechMessageDto, TechMessage>()
// .Ignore(dest => dest.System, dest => dest.SystemId);
//}
public static void AddSwagger(this IServiceCollection services, IConfiguration configuration) public static void AddSwagger(this IServiceCollection services, IConfiguration configuration)
{ {
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>

View File

@ -26,8 +26,6 @@ public class Startup
services.AddJWTAuthentication(Configuration); services.AddJWTAuthentication(Configuration);
services.AddMemoryCache(); services.AddMemoryCache();
services.AddServices(); services.AddServices();
//DependencyInjection.MapsterSetup();
} }

убрать

убрать
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

View File

@ -19,6 +19,7 @@
"password": 12345, "password": 12345,
"clientId": "webapi", "clientId": "webapi",
"grantType": "password", "grantType": "password",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "7d9f3574-6574-4ca3-845a-0276eb4aa8f6" "http://schemas.xmlsoap.org/ws/2005/05/identity /claims/nameidentifier": "7d9f3574-6574-4ca3-845a-0276eb4aa8f6"
} },
"ClientUrl": "http://localhost:5000/"
Review

убрать

убрать
} }

View File

@ -3,16 +3,17 @@ using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces; using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Models; using DD.Persistence.Models;
using DD.Persistence.Models.Requests; using DD.Persistence.Models.Requests;
using DD.Persistence.Client.Clients.Interfaces.Refit;
namespace DD.Persistence.Client.Clients; namespace DD.Persistence.Client.Clients;
public class ChangeLogClient : BaseClient, IChangeLogClient public class ChangeLogClient : BaseClient, IChangeLogClient
{ {
private readonly Interfaces.Refit.IRefitChangeLogClient refitChangeLogClient; private readonly IRefitChangeLogClient refitChangeLogClient;
public ChangeLogClient(Interfaces.Refit.IRefitChangeLogClient refitChangeLogClient, ILogger<ChangeLogClient> logger) : base(logger) public ChangeLogClient(IRefitClientFactory<IRefitChangeLogClient> refitClientFactory, ILogger<ChangeLogClient> logger) : base(logger)
{ {
this.refitChangeLogClient = refitChangeLogClient; this.refitChangeLogClient = refitClientFactory.Create();
} }
public async Task<int> ClearAndAddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token) public async Task<int> ClearAndAddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token)
{ {

View File

@ -9,9 +9,9 @@ public class DataSourceSystemClient : BaseClient, IDataSourceSystemClient
{ {
private readonly IRefitDataSourceSystemClient dataSourceSystemClient; private readonly IRefitDataSourceSystemClient dataSourceSystemClient;
public DataSourceSystemClient(IRefitDataSourceSystemClient dataSourceSystemClient, ILogger<DataSourceSystemClient> logger) : base(logger) public DataSourceSystemClient(IRefitClientFactory<IRefitDataSourceSystemClient> dataSourceSystemClientFactory, ILogger<DataSourceSystemClient> logger) : base(logger)
{ {
this.dataSourceSystemClient = dataSourceSystemClient; this.dataSourceSystemClient = dataSourceSystemClientFactory.Create();
} }
public async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token) public async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)

View File

@ -6,7 +6,7 @@ namespace DD.Persistence.Client.Clients.Interfaces;
/// Клиент для работы с временными данными /// Клиент для работы с временными данными
/// </summary> /// </summary>
/// <typeparam name="TDto"></typeparam> /// <typeparam name="TDto"></typeparam>
public interface ITimeSeriesClient<TDto> : IDisposable where TDto : class, new() public interface ITimeSeriesClient<TDto> : IDisposable where TDto : class, ITimeSeriesAbstractDto
{ {
/// <summary> /// <summary>
/// Добавление записей /// Добавление записей

View File

@ -4,7 +4,7 @@ using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit; namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitChangeLogClient : IDisposable public interface IRefitChangeLogClient : IRefitClient, IDisposable
{ {
private const string BaseRoute = "/api/ChangeLog"; private const string BaseRoute = "/api/ChangeLog";

View File

@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitClient
{
}

View File

@ -2,7 +2,7 @@
using Refit; using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit; namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitDataSourceSystemClient : IDisposable public interface IRefitDataSourceSystemClient : IRefitClient, IDisposable
{ {
private const string BaseRoute = "/api/dataSourceSystem"; private const string BaseRoute = "/api/dataSourceSystem";

View File

@ -3,7 +3,7 @@ using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit; namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitSetpointClient : IDisposable public interface IRefitSetpointClient : IRefitClient, IDisposable
{ {
private const string BaseRoute = "/api/setpoint"; private const string BaseRoute = "/api/setpoint";

View File

@ -5,7 +5,7 @@ using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit namespace DD.Persistence.Client.Clients.Interfaces.Refit
{ {
public interface IRefitTechMessagesClient : IDisposable public interface IRefitTechMessagesClient : IRefitClient, IDisposable
{ {
private const string BaseRoute = "/api/techMessages"; private const string BaseRoute = "/api/techMessages";

View File

@ -2,8 +2,8 @@ using DD.Persistence.Models;
using Refit; using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit; namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitTimeSeriesClient<TDto> : IDisposable public interface IRefitTimeSeriesClient<TDto> : IRefitClient, IDisposable
where TDto : class, new() where TDto : class, ITimeSeriesAbstractDto
{ {
private const string BaseRoute = "/api/dataSaub"; private const string BaseRoute = "/api/dataSaub";

View File

@ -3,7 +3,7 @@ using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit; namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitTimestampedSetClient : IDisposable public interface IRefitTimestampedSetClient : IRefitClient, IDisposable
{ {
private const string baseUrl = "/api/TimestampedSet/{idDiscriminator}"; private const string baseUrl = "/api/TimestampedSet/{idDiscriminator}";

View File

@ -3,7 +3,7 @@ using DD.Persistence.Models;
using Refit; using Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit; namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitWitsDataClient : IDisposable public interface IRefitWitsDataClient : IRefitClient, IDisposable
{ {
private const string BaseRoute = "/api/witsData"; private const string BaseRoute = "/api/witsData";

View File

@ -10,9 +10,9 @@ public class SetpointClient : BaseClient, ISetpointClient
{ {
private readonly IRefitSetpointClient refitSetpointClient; private readonly IRefitSetpointClient refitSetpointClient;
public SetpointClient(IRefitSetpointClient refitSetpointClient, ILogger<SetpointClient> logger) : base(logger) public SetpointClient(IRefitClientFactory<IRefitSetpointClient> refitSetpointClientFactory, ILogger<SetpointClient> logger) : base(logger)
{ {
this.refitSetpointClient = refitSetpointClient; this.refitSetpointClient = refitSetpointClientFactory.Create();
} }
public async Task<IEnumerable<SetpointValueDto>> GetCurrent(IEnumerable<Guid> setpointKeys, CancellationToken token) public async Task<IEnumerable<SetpointValueDto>> GetCurrent(IEnumerable<Guid> setpointKeys, CancellationToken token)

View File

@ -11,9 +11,9 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
{ {
private readonly IRefitTechMessagesClient refitTechMessagesClient; private readonly IRefitTechMessagesClient refitTechMessagesClient;
public TechMessagesClient(IRefitTechMessagesClient refitTechMessagesClient, ILogger<TechMessagesClient> logger) : base(logger) public TechMessagesClient(IRefitClientFactory<IRefitTechMessagesClient> refitTechMessagesClientFactory, ILogger<TechMessagesClient> logger) : base(logger)
{ {
this.refitTechMessagesClient = refitTechMessagesClient; this.refitTechMessagesClient = refitTechMessagesClientFactory.Create();
} }
public async Task<PaginationContainer<TechMessageDto>> GetPage(PaginationRequest request, CancellationToken token) public async Task<PaginationContainer<TechMessageDto>> GetPage(PaginationRequest request, CancellationToken token)

View File

@ -5,13 +5,13 @@ using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models; using DD.Persistence.Models;
namespace DD.Persistence.Client.Clients; namespace DD.Persistence.Client.Clients;
public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where TDto : class, new() public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where TDto : class, ITimeSeriesAbstractDto
{ {
private readonly IRefitTimeSeriesClient<TDto> timeSeriesClient; private readonly IRefitTimeSeriesClient<TDto> timeSeriesClient;
public TimeSeriesClient(IRefitTimeSeriesClient<TDto> refitTechMessagesClient, ILogger<TimeSeriesClient<TDto>> logger) : base(logger) public TimeSeriesClient(IRefitClientFactory<IRefitTimeSeriesClient<TDto>> refitTechMessagesClientFactory, ILogger<TimeSeriesClient<TDto>> logger) : base(logger)
{ {
this.timeSeriesClient = refitTechMessagesClient; this.timeSeriesClient = refitTechMessagesClientFactory.Create();
} }
public async Task<int> AddRange(IEnumerable<TDto> dtos, CancellationToken token) public async Task<int> AddRange(IEnumerable<TDto> dtos, CancellationToken token)

View File

@ -9,9 +9,9 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
{ {
private readonly IRefitTimestampedSetClient refitTimestampedSetClient; private readonly IRefitTimestampedSetClient refitTimestampedSetClient;
public TimestampedSetClient(IRefitTimestampedSetClient refitTimestampedSetClient, ILogger<TimestampedSetClient> logger) : base(logger) public TimestampedSetClient(IRefitClientFactory<IRefitTimestampedSetClient> refitTimestampedSetClientFactory, ILogger<TimestampedSetClient> logger) : base(logger)
{ {
this.refitTimestampedSetClient = refitTimestampedSetClient; this.refitTimestampedSetClient = refitTimestampedSetClientFactory.Create();
} }
public async Task<int> AddRange(Guid idDiscriminator, IEnumerable<TimestampedSetDto> sets, CancellationToken token) public async Task<int> AddRange(Guid idDiscriminator, IEnumerable<TimestampedSetDto> sets, CancellationToken token)

View File

@ -9,9 +9,9 @@ public class WitsDataClient : BaseClient, IWitsDataClient
{ {
private readonly IRefitWitsDataClient refitWitsDataClient; private readonly IRefitWitsDataClient refitWitsDataClient;
public WitsDataClient(IRefitWitsDataClient refitWitsDataClient, ILogger<WitsDataClient> logger) : base(logger) public WitsDataClient(IRefitClientFactory<IRefitWitsDataClient> refitWitsDataClientFactory, ILogger<WitsDataClient> logger) : base(logger)
{ {
this.refitWitsDataClient = refitWitsDataClient; this.refitWitsDataClient = refitWitsDataClientFactory.Create();
} }
public async Task<int> AddRange(IEnumerable<WitsDataDto> dtos, CancellationToken token) public async Task<int> AddRange(IEnumerable<WitsDataDto> dtos, CancellationToken token)

View File

@ -53,6 +53,7 @@
<PackageReference Include="Refit" Version="8.0.0" /> <PackageReference Include="Refit" Version="8.0.0" />
<PackageReference Include="Refit.HttpClientFactory" Version="8.0.0" /> <PackageReference Include="Refit.HttpClientFactory" Version="8.0.0" />
<PackageReference Include="RestSharp" Version="112.1.0" /> <PackageReference Include="RestSharp" Version="112.1.0" />
Review

проверить необходимость

проверить необходимость
Review
image
<img width="760" alt="image" src="attachments/ce817d0b-ffdb-484f-8413-72523bf0cf3a">
<PackageReference Include="System.Configuration.ConfigurationManager" Version="9.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.3.0" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.3.0" />
Review

проверить необходимость

проверить необходимость
Review

Необходимость только для этого:

Необходимость только для этого:
</ItemGroup> </ItemGroup>

View File

@ -0,0 +1,30 @@
using DD.Persistence.Client.Clients;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Models;
using Microsoft.Extensions.DependencyInjection;
namespace DD.Persistence.Client;
/// <summary>
///
/// </summary>
public static class DependencyInjection
{
/// <summary>
///
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddPersistenceClients(this IServiceCollection services)
{
services.AddTransient(typeof(IRefitClientFactory<>), typeof(RefitClientFactory<>));
services.AddTransient<IChangeLogClient, ChangeLogClient>();
services.AddTransient<IDataSourceSystemClient, DataSourceSystemClient>();
services.AddTransient<ISetpointClient, SetpointClient>();
services.AddTransient<ITechMessagesClient, TechMessagesClient>();
services.AddTransient<ITimeSeriesClient<DataSaubDto>, TimeSeriesClient<DataSaubDto>>();
services.AddTransient<ITimestampedSetClient, TimestampedSetClient>();
services.AddTransient<IWitsDataClient, WitsDataClient>();
return services;
}
}

View File

@ -0,0 +1,16 @@
using DD.Persistence.Client.Clients.Interfaces.Refit;
Review

Лишние namespace-ы

Лишние namespace-ы
namespace DD.Persistence.Client;
/// <summary>
/// Интерфейс для фабрики, которая создает refit-клиентов
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IRefitClientFactory<T> where T : IRefitClient
{
/// <summary>
/// Создание refit-клиента
/// </summary>
/// <returns></returns>
public T Create();
}

View File

@ -1,146 +0,0 @@
using Microsoft.Extensions.Configuration;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients;
using DD.Persistence.Client.Helpers;
using Refit;
using DD.Persistence.Factories;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;
namespace DD.Persistence.Client
{
/// <summary>
/// Фабрика клиентов для доступа к Persistence - сервису
/// </summary>
public class PersistenceClientFactory
{
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};
private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
private readonly IServiceProvider provider;
private HttpClient httpClient;
public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IServiceProvider provider, IConfiguration configuration)
{
this.provider = provider;
httpClient = httpClientFactory.CreateClient();
httpClient.Authorize(configuration);
}
public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IAuthTokenFactory authTokenFactory, IServiceProvider provider, IConfiguration configuration)
{
this.provider = provider;
httpClient = httpClientFactory.CreateClient();
var token = authTokenFactory.GetToken();
httpClient.Authorize(token);
}
/// <summary>
/// Получить клиент для работы с уставками
/// </summary>
/// <returns></returns>
public ISetpointClient GetSetpointClient()
{
var logger = provider.GetRequiredService<ILogger<SetpointClient>>();
var restClient = RestService.For<IRefitSetpointClient>(httpClient, RefitSettings);
var client = new SetpointClient(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы с технологическими сообщениями
/// </summary>
/// <returns></returns>
public ITechMessagesClient GetTechMessagesClient()
{
var logger = provider.GetRequiredService<ILogger<TechMessagesClient>>();
var restClient = RestService.For<IRefitTechMessagesClient>(httpClient, RefitSettings);
var client = new TechMessagesClient(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы с временными данными
/// </summary>
/// <typeparam name="TDto"></typeparam>
/// <returns></returns>
public ITimeSeriesClient<TDto> GetTimeSeriesClient<TDto>()
where TDto : class, new()
{
var logger = provider.GetRequiredService<ILogger<TimeSeriesClient<TDto>>>();
var restClient = RestService.For<IRefitTimeSeriesClient<TDto>>(httpClient, RefitSettings);
var client = new TimeSeriesClient<TDto>(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы с данными с отметкой времени
/// </summary>
/// <returns></returns>
public ITimestampedSetClient GetTimestampedSetClient()
{
var logger = provider.GetRequiredService<ILogger<TimestampedSetClient>>();
var restClient = RestService.For<IRefitTimestampedSetClient>(httpClient, RefitSettings);
var client = new TimestampedSetClient(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы с записями ChangeLog
/// </summary>
/// <returns></returns>
public IChangeLogClient GetChangeLogClient()
{
var logger = provider.GetRequiredService<ILogger<ChangeLogClient>>();
var restClient = RestService.For<IRefitChangeLogClient>(httpClient, RefitSettings);
var client = new ChangeLogClient(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы c параметрами Wits
/// </summary>
/// <returns></returns>
public IWitsDataClient GetWitsDataClient()
{
var logger = provider.GetRequiredService<ILogger<WitsDataClient>>();
var restClient = RestService.For<IRefitWitsDataClient>(httpClient, RefitSettings);
var client = new WitsDataClient(restClient, logger);
return client;
}
/// <summary>
/// Получить клиент для работы c системами
/// </summary>
/// <returns></returns>
public IDataSourceSystemClient GetDataSourceSystemClient()
{
var logger = provider.GetRequiredService<ILogger<DataSourceSystemClient>>();
var restClient = RestService.For<IRefitDataSourceSystemClient>(httpClient, RefitSettings);
var client = new DataSourceSystemClient(restClient, logger);
return client;
}
}
}

View File

@ -0,0 +1,52 @@
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Client.Helpers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Refit;
using System.Configuration;
using System.Text.Json;
namespace DD.Persistence.Client;
Review

А не нужно ли добавить в проект <NoWarn>$(NoWarn);1591</NoWarn>? У меня всё в варнингах почему-то

А не нужно ли добавить в проект `<NoWarn>$(NoWarn);1591</NoWarn>`? У меня всё в варнингах почему-то
Review

Создала отдельную задачу для этого:
https://project.ddrilling.ru/projects/persistance-service/work_packages/746/activity

Создала отдельную задачу для этого: https://project.ddrilling.ru/projects/persistance-service/work_packages/746/activity
/// <summary>
/// Фабрика, которая создает refit-клиентов
/// </summary>
/// <typeparam name="T"></typeparam>
public class RefitClientFactory<T> : IRefitClientFactory<T> where T : IRefitClient
{
private HttpClient client;
private RefitSettings refitSettings;
/// <inheritdoc/>
public RefitClientFactory(IConfiguration configuration, ILogger<IRefitClientFactory<T>> logger, HttpClient client)

Пустой summary

Пустой summary
{
//this.client = factory.CreateClient();
this.client = client;
var baseUrl = configuration.GetSection("ClientUrl").Get<string>();
if (String.IsNullOrEmpty(baseUrl))
{
var exception = new SettingsPropertyNotFoundException("В настройках конфигурации не указан адрес Persistence сервиса.");
logger.LogError(exception.Message);
throw exception;
}
client.BaseAddress = new Uri(baseUrl);
JsonSerializerOptions JsonSerializerOptions = new()
{
Review

Данный метод тянет аутентификационные данные с конфигов и авторизует Http - клиента. Это нужно для тестов, но нужно ли для непосредственного использования фабрики сторонними сервисами? Если они передают уже авторизованного Http клиента - то нужно предусмотреть вызов client.Authorize(configuration); только для тестов. Например проверкой Environment, либо через конфиг

Данный метод тянет аутентификационные данные с конфигов и авторизует Http - клиента. Это нужно для тестов, но нужно ли для непосредственного использования фабрики сторонними сервисами? Если они передают уже авторизованного Http клиента - то нужно предусмотреть вызов `client.Authorize(configuration);` только для тестов. Например проверкой Environment, либо через конфиг
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};
refitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
}
/// <summary>
/// создание клиента
/// </summary>
/// <returns></returns>
public T Create()
{
return RestService.For<T>(client, refitSettings);
}
}

View File

@ -7,6 +7,11 @@ using DD.Persistence.Models.Requests;
using Xunit; using Xunit;
using DD.Persistence.Client.Clients.Interfaces; using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client; using DD.Persistence.Client;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Client.Clients;
using Microsoft.Extensions.Logging;
using Refit;
using System.Net.Http;
namespace DD.Persistence.IntegrationTests.Controllers; namespace DD.Persistence.IntegrationTests.Controllers;
public class ChangeLogControllerTest : BaseIntegrationTest public class ChangeLogControllerTest : BaseIntegrationTest
@ -16,10 +21,12 @@ public class ChangeLogControllerTest : BaseIntegrationTest
public ChangeLogControllerTest(WebAppFactoryFixture factory) : base(factory) public ChangeLogControllerTest(WebAppFactoryFixture factory) : base(factory)
{ {
var persistenceClientFactory = scope.ServiceProvider var refitClientFactory = scope.ServiceProvider
.GetRequiredService<PersistenceClientFactory>(); .GetRequiredService<IRefitClientFactory<IRefitChangeLogClient>>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<ChangeLogClient>>();
client = persistenceClientFactory.GetChangeLogClient(); client = scope.ServiceProvider
.GetRequiredService<IChangeLogClient>();
} }
[Fact] [Fact]

View File

@ -6,6 +6,8 @@ using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Database.Entity; using DD.Persistence.Database.Entity;
using DD.Persistence.Models; using DD.Persistence.Models;
using Xunit; using Xunit;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using Microsoft.Extensions.Logging;
namespace DD.Persistence.IntegrationTests.Controllers namespace DD.Persistence.IntegrationTests.Controllers
{ {
@ -16,11 +18,12 @@ namespace DD.Persistence.IntegrationTests.Controllers
private readonly IMemoryCache memoryCache; private readonly IMemoryCache memoryCache;
public DataSourceSystemControllerTest(WebAppFactoryFixture factory) : base(factory) public DataSourceSystemControllerTest(WebAppFactoryFixture factory) : base(factory)
{ {
var scope = factory.Services.CreateScope(); var refitClientFactory = scope.ServiceProvider
var persistenceClientFactory = scope.ServiceProvider .GetRequiredService<IRefitClientFactory<IRefitDataSourceSystemClient>>();
.GetRequiredService<PersistenceClientFactory>(); var logger = scope.ServiceProvider.GetRequiredService<ILogger<DataSourceSystemClient>>();
dataSourceSystemClient = persistenceClientFactory.GetDataSourceSystemClient(); dataSourceSystemClient = scope.ServiceProvider
.GetRequiredService<IDataSourceSystemClient>();
memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>(); memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
} }

View File

@ -4,6 +4,9 @@ using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Database.Model; using DD.Persistence.Database.Model;
using System.Net; using System.Net;
using Xunit; using Xunit;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Client.Clients;
using Microsoft.Extensions.Logging;
namespace DD.Persistence.IntegrationTests.Controllers namespace DD.Persistence.IntegrationTests.Controllers
{ {
@ -17,11 +20,12 @@ namespace DD.Persistence.IntegrationTests.Controllers
} }
public SetpointControllerTest(WebAppFactoryFixture factory) : base(factory) public SetpointControllerTest(WebAppFactoryFixture factory) : base(factory)
{ {
var scope = factory.Services.CreateScope(); var refitClientFactory = scope.ServiceProvider
var persistenceClientFactory = scope.ServiceProvider .GetRequiredService<IRefitClientFactory<IRefitSetpointClient>>();
.GetRequiredService<PersistenceClientFactory>(); var logger = scope.ServiceProvider.GetRequiredService<ILogger<SetpointClient>>();
setpointClient = persistenceClientFactory.GetSetpointClient(); setpointClient = scope.ServiceProvider
.GetRequiredService<ISetpointClient>();
} }
[Fact] [Fact]

View File

@ -1,38 +1,41 @@
using Microsoft.Extensions.Caching.Memory; using DD.Persistence.Client;
using Microsoft.Extensions.DependencyInjection; using DD.Persistence.Client.Clients;
using DD.Persistence.Client;
using DD.Persistence.Client.Clients.Interfaces; using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Database.Entity; using DD.Persistence.Database.Entity;
using DD.Persistence.Models; using DD.Persistence.Models;
using DD.Persistence.Models.Enumerations; using DD.Persistence.Models.Enumerations;
using DD.Persistence.Models.Requests; using DD.Persistence.Models.Requests;
using System.Net; using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit; using Xunit;
namespace DD.Persistence.IntegrationTests.Controllers namespace DD.Persistence.IntegrationTests.Controllers
{ {
public class TechMessagesControllerTest : BaseIntegrationTest public class TechMessagesControllerTest : BaseIntegrationTest
{ {
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey"; private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
private readonly ITechMessagesClient techMessagesClient; private readonly ITechMessagesClient techMessagesClient;
private readonly IMemoryCache memoryCache; private readonly IMemoryCache memoryCache;
public TechMessagesControllerTest(WebAppFactoryFixture factory) : base(factory) public TechMessagesControllerTest(WebAppFactoryFixture factory) : base(factory)
{ {
var scope = factory.Services.CreateScope(); var refitClientFactory = scope.ServiceProvider
var persistenceClientFactory = scope.ServiceProvider .GetRequiredService<IRefitClientFactory<IRefitTechMessagesClient>>();
.GetRequiredService<PersistenceClientFactory>(); var logger = scope.ServiceProvider.GetRequiredService<ILogger<TechMessagesClient>>();
techMessagesClient = persistenceClientFactory.GetTechMessagesClient(); techMessagesClient = scope.ServiceProvider
memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>(); .GetRequiredService<ITechMessagesClient>();
} memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
}
[Fact] [Fact]
public async Task GetPage_returns_success() public async Task GetPage_returns_success()
{ {
//arrange //arrange
memoryCache.Remove(SystemCacheKey); memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>(); dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>(); dbContext.CleanupDbSet<DataSourceSystem>();
var requestDto = new PaginationRequest() var requestDto = new PaginationRequest()
{ {
@ -44,235 +47,235 @@ namespace DD.Persistence.IntegrationTests.Controllers
//act //act
var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None); var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None);
//assert //assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.Empty(response.Items); Assert.Empty(response.Items);
Assert.Equal(requestDto.Skip, response.Skip); Assert.Equal(requestDto.Skip, response.Skip);
Assert.Equal(requestDto.Take, response.Take); Assert.Equal(requestDto.Take, response.Take);
} }
[Fact] [Fact]
public async Task GetPage_AfterSave_returns_success() public async Task GetPage_AfterSave_returns_success()
{ {
//arrange //arrange
var dtos = await InsertRange(Guid.NewGuid()); var dtos = await InsertRange(Guid.NewGuid());
var dtosCount = dtos.Count(); var dtosCount = dtos.Count();
var requestDto = new PaginationRequest() var requestDto = new PaginationRequest()
{ {
Skip = 0, Skip = 0,
Take = 2, Take = 2,
SortSettings = nameof(TechMessage.CategoryId) SortSettings = nameof(TechMessage.CategoryId)
}; };
//act //act
var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None); var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None);
//assert //assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.Equal(dtosCount, response.Count); Assert.Equal(dtosCount, response.Count);
} }
[Fact] [Fact]
public async Task InsertRange_returns_success() public async Task InsertRange_returns_success()
{ {
await InsertRange(Guid.NewGuid()); await InsertRange(Guid.NewGuid());
} }
[Fact] [Fact]
public async Task InsertRange_returns_BadRequest() public async Task InsertRange_returns_BadRequest()
{ {
//arrange //arrange
const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса"; const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса";
var systemId = Guid.NewGuid(); var systemId = Guid.NewGuid();
var dtos = new List<TechMessageDto>() var dtos = new List<TechMessageDto>()
{ {
new TechMessageDto() new TechMessageDto()
{ {
EventId = Guid.NewGuid(), EventId = Guid.NewGuid(),
CategoryId = -1, // < 0 CategoryId = -1, // < 0
Timestamp = DateTimeOffset.UtcNow, Timestamp = DateTimeOffset.UtcNow,
Text = string.Empty, // length < 0 Text = string.Empty, // length < 0
EventState = EventState.Triggered EventState = EventState.Triggered
} }
}; };
try try
{ {
//act //act
var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None); var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None);
} }
catch (Exception ex) catch (Exception ex)
{ {
//assert //assert
Assert.Equal(exceptionMessage, ex.Message); Assert.Equal(exceptionMessage, ex.Message);
} }
} }
[Fact] [Fact]
public async Task GetSystems_returns_success() public async Task GetSystems_returns_success()
{ {
//arrange //arrange
memoryCache.Remove(SystemCacheKey); memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>(); dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>(); dbContext.CleanupDbSet<DataSourceSystem>();
//act //act
var response = await techMessagesClient.GetSystems(CancellationToken.None); var response = await techMessagesClient.GetSystems(CancellationToken.None);
//assert //assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.Empty(response); Assert.Empty(response);
} }
[Fact] [Fact]
public async Task GetSystems_AfterSave_returns_success() public async Task GetSystems_AfterSave_returns_success()
{ {
//arrange //arrange
await InsertRange(Guid.NewGuid()); await InsertRange(Guid.NewGuid());
//act //act
var response = await techMessagesClient.GetSystems(CancellationToken.None); var response = await techMessagesClient.GetSystems(CancellationToken.None);
//assert //assert
Assert.NotNull(response); Assert.NotNull(response);
var expectedSystemCount = 1; var expectedSystemCount = 1;
Assert.Equal(expectedSystemCount, response!.Count()); Assert.Equal(expectedSystemCount, response!.Count());
} }
[Fact] [Fact]
public async Task GetStatistics_returns_success() public async Task GetStatistics_returns_success()
{ {
//arrange //arrange
memoryCache.Remove(SystemCacheKey); memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>(); dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>(); dbContext.CleanupDbSet<DataSourceSystem>();
var categoryIds = new [] { 1, 2 }; var categoryIds = new[] { 1, 2 };
var systemIds = new [] { Guid.NewGuid() }; var systemIds = new[] { Guid.NewGuid() };
//act //act
var response = await techMessagesClient.GetStatistics(systemIds, categoryIds, CancellationToken.None); var response = await techMessagesClient.GetStatistics(systemIds, categoryIds, CancellationToken.None);
//assert //assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.Empty(response); Assert.Empty(response);
} }
[Fact] [Fact]
public async Task GetStatistics_AfterSave_returns_success() public async Task GetStatistics_AfterSave_returns_success()
{ {
//arrange //arrange
var categoryIds = new[] { 1 }; var categoryIds = new[] { 1 };
var systemId = Guid.NewGuid(); var systemId = Guid.NewGuid();
var dtos = await InsertRange(systemId); var dtos = await InsertRange(systemId);
var filteredDtos = dtos.Where(e => categoryIds.Contains(e.CategoryId)); var filteredDtos = dtos.Where(e => categoryIds.Contains(e.CategoryId));
//act //act
var response = await techMessagesClient.GetStatistics([systemId], categoryIds, CancellationToken.None); var response = await techMessagesClient.GetStatistics([systemId], categoryIds, CancellationToken.None);
//assert //assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.NotEmpty(response); Assert.NotEmpty(response);
var categories = response var categories = response
.FirstOrDefault()!.Categories .FirstOrDefault()!.Categories
.Count(); .Count();
Assert.Equal(filteredDtos.Count(), categories); Assert.Equal(filteredDtos.Count(), categories);
} }
[Fact] [Fact]
public async Task GetDatesRange_returns_NoContent() public async Task GetDatesRange_returns_NoContent()
{ {
//arrange //arrange
memoryCache.Remove(SystemCacheKey); memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>(); dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>(); dbContext.CleanupDbSet<DataSourceSystem>();
//act //act
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
//assert //assert
Assert.Null(response); Assert.Null(response);
} }
[Fact] [Fact]
public async Task GetDatesRange_AfterSave_returns_success() public async Task GetDatesRange_AfterSave_returns_success()
{ {
//arrange //arrange
await InsertRange(Guid.NewGuid()); await InsertRange(Guid.NewGuid());
//act //act
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
//assert //assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.NotNull(response?.From); Assert.NotNull(response?.From);
Assert.NotNull(response?.To); Assert.NotNull(response?.To);
} }
// [Fact] // [Fact]
// public async Task GetPart_returns_success() // public async Task GetPart_returns_success()
// { // {
// //arrange // //arrange
// var dateBegin = DateTimeOffset.UtcNow; // var dateBegin = DateTimeOffset.UtcNow;
// var take = 2; // var take = 2;
// //act // //act
// var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None); // var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None);
// //assert // //assert
// Assert.NotNull(response); // Assert.NotNull(response);
// Assert.Empty(response); // Assert.Empty(response);
//} //}
[Fact] [Fact]
public async Task GetPart_AfterSave_returns_success() public async Task GetPart_AfterSave_returns_success()
{ {
//arrange //arrange
var dateBegin = DateTimeOffset.UtcNow; var dateBegin = DateTimeOffset.UtcNow;
var take = 1; var take = 1;
await InsertRange(Guid.NewGuid()); await InsertRange(Guid.NewGuid());
//act //act
var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None); var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None);
//assert //assert
Assert.NotNull(response); Assert.NotNull(response);
Assert.NotEmpty(response); Assert.NotEmpty(response);
} }
private async Task<IEnumerable<TechMessageDto>> InsertRange(Guid systemId) private async Task<IEnumerable<TechMessageDto>> InsertRange(Guid systemId)
{ {
//arrange //arrange
memoryCache.Remove(SystemCacheKey); memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>(); dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>(); dbContext.CleanupDbSet<DataSourceSystem>();
var dtos = new List<TechMessageDto>() var dtos = new List<TechMessageDto>()
{ {
new TechMessageDto() new TechMessageDto()
{ {
EventId = Guid.NewGuid(), EventId = Guid.NewGuid(),
CategoryId = 1, CategoryId = 1,
Timestamp = DateTimeOffset.UtcNow, Timestamp = DateTimeOffset.UtcNow,
Text = nameof(TechMessageDto.Text), Text = nameof(TechMessageDto.Text),
EventState = Models.Enumerations.EventState.Triggered EventState = Models.Enumerations.EventState.Triggered
}, },
new TechMessageDto() new TechMessageDto()
{ {
EventId = Guid.NewGuid(), EventId = Guid.NewGuid(),
CategoryId = 2, CategoryId = 2,
Timestamp = DateTimeOffset.UtcNow, Timestamp = DateTimeOffset.UtcNow,
Text = nameof(TechMessageDto.Text), Text = nameof(TechMessageDto.Text),
EventState = Models.Enumerations.EventState.Triggered EventState = Models.Enumerations.EventState.Triggered
} }
}; };
//act //act
var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None); var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None);
//assert //assert
Assert.Equal(dtos.Count, response); Assert.Equal(dtos.Count, response);
return dtos; return dtos;
} }

View File

@ -1,16 +1,19 @@
using DD.Persistence.Client;
using DD.Persistence.Client.Clients;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Database.Model;
using DD.Persistence.Models;
using Mapster; using Mapster;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using DD.Persistence.Client; using Microsoft.Extensions.Logging;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Database.Model;
using System.Net;
using Xunit; using Xunit;
namespace DD.Persistence.IntegrationTests.Controllers; namespace DD.Persistence.IntegrationTests.Controllers;
public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrationTest public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrationTest
where TEntity : class, ITimestampedData, new() where TEntity : class, ITimestampedData, new()
where TDto : class, new() where TDto : class, ITimeSeriesAbstractDto, new()
{ {
private readonly ITimeSeriesClient<TDto> timeSeriesClient; private readonly ITimeSeriesClient<TDto> timeSeriesClient;
@ -18,11 +21,12 @@ public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrat
{ {
dbContext.CleanupDbSet<TEntity>(); dbContext.CleanupDbSet<TEntity>();
var scope = factory.Services.CreateScope(); var refitClientFactory = scope.ServiceProvider
var persistenceClientFactory = scope.ServiceProvider .GetRequiredService<IRefitClientFactory<IRefitTimeSeriesClient<TDto>>>();
.GetRequiredService<PersistenceClientFactory>(); var logger = scope.ServiceProvider.GetRequiredService<ILogger<TimeSeriesClient<TDto>>>();
timeSeriesClient = persistenceClientFactory.GetTimeSeriesClient<TDto>(); timeSeriesClient = scope.ServiceProvider
.GetRequiredService<ITimeSeriesClient<TDto>>();
} }
public async Task InsertRangeSuccess(TDto dto) public async Task InsertRangeSuccess(TDto dto)

View File

@ -3,6 +3,9 @@ using DD.Persistence.Client;
using DD.Persistence.Client.Clients.Interfaces; using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Models; using DD.Persistence.Models;
using Xunit; using Xunit;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Client.Clients;
using Microsoft.Extensions.Logging;
namespace DD.Persistence.IntegrationTests.Controllers; namespace DD.Persistence.IntegrationTests.Controllers;
public class TimestampedSetControllerTest : BaseIntegrationTest public class TimestampedSetControllerTest : BaseIntegrationTest
@ -11,10 +14,12 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
public TimestampedSetControllerTest(WebAppFactoryFixture factory) : base(factory) public TimestampedSetControllerTest(WebAppFactoryFixture factory) : base(factory)
{ {
var persistenceClientFactory = scope.ServiceProvider var refitClientFactory = scope.ServiceProvider
.GetRequiredService<PersistenceClientFactory>(); .GetRequiredService<IRefitClientFactory<IRefitTimestampedSetClient>>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<TimestampedSetClient>>();
client = persistenceClientFactory.GetTimestampedSetClient(); client = scope.ServiceProvider
.GetRequiredService<ITimestampedSetClient>();
} }
[Fact] [Fact]

View File

@ -1,10 +1,12 @@
using Microsoft.Extensions.DependencyInjection; using DD.Persistence.Client;
using DD.Persistence.Client.Clients;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Database.Entity; using DD.Persistence.Database.Entity;
using DD.Persistence.Models; using DD.Persistence.Models;
using System.Net; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit; using Xunit;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client;
namespace DD.Persistence.IntegrationTests.Controllers; namespace DD.Persistence.IntegrationTests.Controllers;
public class WitsDataControllerTest : BaseIntegrationTest public class WitsDataControllerTest : BaseIntegrationTest
@ -13,11 +15,12 @@ public class WitsDataControllerTest : BaseIntegrationTest
public WitsDataControllerTest(WebAppFactoryFixture factory) : base(factory) public WitsDataControllerTest(WebAppFactoryFixture factory) : base(factory)
{ {
var scope = factory.Services.CreateScope(); var refitClientFactory = scope.ServiceProvider
var persistenceClientFactory = scope.ServiceProvider .GetRequiredService<IRefitClientFactory<IRefitWitsDataClient>>();
.GetRequiredService<PersistenceClientFactory>(); var logger = scope.ServiceProvider.GetRequiredService<ILogger<WitsDataClient>>();
witsDataClient = persistenceClientFactory.GetWitsDataClient(); witsDataClient = scope.ServiceProvider
.GetRequiredService<IWitsDataClient>();
} }
[Fact] [Fact]

View File

@ -1,4 +1,7 @@
namespace DD.Persistence.IntegrationTests using DD.Persistence.Client.Helpers;
using Microsoft.Extensions.Configuration;
namespace DD.Persistence.IntegrationTests
{ {
/// <summary> /// <summary>
/// Фабрика HTTP клиентов для интеграционных тестов /// Фабрика HTTP клиентов для интеграционных тестов
@ -6,14 +9,19 @@
public class TestHttpClientFactory : IHttpClientFactory public class TestHttpClientFactory : IHttpClientFactory
{ {
private readonly WebAppFactoryFixture factory; private readonly WebAppFactoryFixture factory;
private readonly IConfiguration configuration;
public TestHttpClientFactory(WebAppFactoryFixture factory) public TestHttpClientFactory(WebAppFactoryFixture factory, IConfiguration configuration)
{ {
this.factory = factory; this.factory = factory;
this.configuration = configuration;
} }
public HttpClient CreateClient(string name) public HttpClient CreateClient(string name)
{ {
return factory.CreateClient(); var client = factory.CreateClient();
client.Authorize(configuration);
Review

Авторизация должна добавляться клиенту в фабрике. У клиента не должно быть метода ауторайз

Авторизация должна добавляться клиенту в фабрике. У клиента не должно быть метода ауторайз
return client;
} }
} }
} }

View File

@ -11,6 +11,9 @@ using DD.Persistence.Database.Model;
using DD.Persistence.Database.Postgres; using DD.Persistence.Database.Postgres;
using RestSharp; using RestSharp;
using DD.Persistence.App; using DD.Persistence.App;
using DD.Persistence.Client.Helpers;
using DD.Persistence.Factories;
using System.Net;
namespace DD.Persistence.IntegrationTests; namespace DD.Persistence.IntegrationTests;
public class WebAppFactoryFixture : WebApplicationFactory<Program> public class WebAppFactoryFixture : WebApplicationFactory<Program>
@ -40,12 +43,12 @@ public class WebAppFactoryFixture : WebApplicationFactory<Program>
services.AddLogging(builder => builder.AddConsole()); services.AddLogging(builder => builder.AddConsole());
services.RemoveAll<IHttpClientFactory>(); services.RemoveAll<IHttpClientFactory>();
services.AddSingleton<IHttpClientFactory>(provider => services.AddSingleton<IHttpClientFactory>((provider) =>
{ {
return new TestHttpClientFactory(this); return new TestHttpClientFactory(this, provider.GetRequiredService<IConfiguration>());
}); });
services.AddHttpClient();
services.AddSingleton<PersistenceClientFactory>(); services.AddPersistenceClients();
var serviceProvider = services.BuildServiceProvider(); var serviceProvider = services.BuildServiceProvider();