feat: Implement ServiceFactory for dependency injection
- Added ServiceFactory class to manage service registrations and service provider creation. - Implemented a lazy-loaded IServiceProvider to ensure services are only built once. - Prevent further modifications to the service collection after the service provider is created. - Added Provide<T>() method to resolve and retrieve services from the service provider.
This commit is contained in:
@@ -44,7 +44,10 @@ namespace DigitalData.Core.Client
|
|||||||
if (sendWithCookie)
|
if (sendWithCookie)
|
||||||
{
|
{
|
||||||
var cookieHeader = _cookies.GetCookieHeader(requestUri);
|
var cookieHeader = _cookies.GetCookieHeader(requestUri);
|
||||||
requestMessage.Headers.Add("Cookie", cookieHeader);
|
if (!string.IsNullOrWhiteSpace(cookieHeader))
|
||||||
|
{
|
||||||
|
requestMessage.Headers.Add("Cookie", cookieHeader);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add body content if provided
|
// Add body content if provided
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Options" Version="7.0.0" />
|
<PackageReference Include="Microsoft.Extensions.Options" Version="7.0.0" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
21
DigitalData.Core.Client/ServiceFactory.cs
Normal file
21
DigitalData.Core.Client/ServiceFactory.cs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace DigitalData.Core.Client
|
||||||
|
{
|
||||||
|
public static class ServiceFactory
|
||||||
|
{
|
||||||
|
private static readonly IServiceCollection _services = new ServiceCollection();
|
||||||
|
private static readonly Lazy<IServiceProvider> _lazyProvider = new(Build);
|
||||||
|
|
||||||
|
public static IServiceCollection Services => !_lazyProvider.IsValueCreated
|
||||||
|
? _services
|
||||||
|
: throw new InvalidOperationException(
|
||||||
|
"Service provider has already been created. " +
|
||||||
|
"Further modifications to the service collection are not allowed. " +
|
||||||
|
"This is to ensure that the dependency injection container remains in a consistent state.");
|
||||||
|
|
||||||
|
public static IServiceProvider Build() => _services.BuildServiceProvider();
|
||||||
|
|
||||||
|
public static T Provide<T>() where T : notnull => _lazyProvider.Value.GetRequiredService<T>();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,127 +1,35 @@
|
|||||||
using DigitalData.Core.Client;
|
using DigitalData.Core.Abstractions.Client;
|
||||||
using Microsoft.Extensions.Options;
|
using DigitalData.Core.Client;
|
||||||
using Moq;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Moq.Protected;
|
|
||||||
using NUnit.Framework;
|
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Net;
|
|
||||||
using System.Net.Http;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace DigitalData.Core.Tests
|
namespace DigitalData.Core.Tests
|
||||||
{
|
{
|
||||||
[TestFixture]
|
[TestFixture]
|
||||||
public class BaseHttpClientServiceTests
|
public class BaseHttpClientServiceTests
|
||||||
{
|
{
|
||||||
private Mock<HttpMessageHandler> _messageHandlerMock;
|
private IServiceProvider _serviceProvider;
|
||||||
private HttpClient _httpClient;
|
private IBaseHttpClientService _service;
|
||||||
private CookieContainer _cookieContainer;
|
|
||||||
private Mock<IOptions<HttpClientOptions>> _optionsMock;
|
|
||||||
private BaseHttpClientService _service;
|
|
||||||
|
|
||||||
[SetUp]
|
[SetUp]
|
||||||
public void SetUp()
|
public void SetUp()
|
||||||
{
|
{
|
||||||
_messageHandlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
|
_serviceProvider = new ServiceCollection()
|
||||||
_httpClient = new HttpClient(_messageHandlerMock.Object);
|
.AddHttpClientService("https://jsonplaceholder.typicode.com/todos")
|
||||||
_cookieContainer = new CookieContainer();
|
.BuildServiceProvider();
|
||||||
_optionsMock = new Mock<IOptions<HttpClientOptions>>();
|
|
||||||
_optionsMock.Setup(o => o.Value).Returns(new HttpClientOptions { Uri = "https://example.com" });
|
|
||||||
|
|
||||||
_service = new BaseHttpClientService(_httpClient, _cookieContainer, _optionsMock.Object);
|
_service = _serviceProvider.GetRequiredService<IBaseHttpClientService>();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public void GetCookies_ShouldReturnCookies()
|
public async Task FetchJsonAsync_ShouldReturnJsonResponse()
|
||||||
{
|
{
|
||||||
// Arrange
|
|
||||||
var uri = new Uri("https://example.com/test");
|
|
||||||
_cookieContainer.Add(uri, new Cookie("test", "value"));
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var cookies = _service.GetCookies("/test");
|
var expectedUserId = (int) await _service.FetchAsync("/1", sendWithCookie: false, saveCookie: false)
|
||||||
|
.ThenAsync(res => res.Json())
|
||||||
|
.ThenAsync(todo => todo.userId);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.AreEqual(1, cookies.Count);
|
Assert.That(expectedUserId, Is.EqualTo(1), "The userId of the fetched JSON object should be 1.");
|
||||||
Assert.AreEqual("test", cookies[0].Name);
|
|
||||||
Assert.AreEqual("value", cookies[0].Value);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Test]
|
|
||||||
public async Task FetchAsync_ShouldSendRequestWithMethodAndBody()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
|
|
||||||
_messageHandlerMock
|
|
||||||
.Protected()
|
|
||||||
.Setup<Task<HttpResponseMessage>>(
|
|
||||||
"SendAsync",
|
|
||||||
ItExpr.IsAny<HttpRequestMessage>(),
|
|
||||||
ItExpr.IsAny<CancellationToken>()
|
|
||||||
)
|
|
||||||
.ReturnsAsync(responseMessage);
|
|
||||||
|
|
||||||
var bodyContent = new StringContent("test body");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await _service.FetchAsync("/test", HttpMethod.Post, body: bodyContent);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
|
||||||
_messageHandlerMock.Protected().Verify(
|
|
||||||
"SendAsync",
|
|
||||||
Times.Once(),
|
|
||||||
ItExpr.Is<HttpRequestMessage>(req =>
|
|
||||||
req.Method == HttpMethod.Post &&
|
|
||||||
req.RequestUri == new Uri("https://example.com/test") &&
|
|
||||||
req.Content == bodyContent),
|
|
||||||
ItExpr.IsAny<CancellationToken>()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Test]
|
|
||||||
public async Task FetchAsync_ShouldSendRequestWithForm()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
|
|
||||||
_messageHandlerMock
|
|
||||||
.Protected()
|
|
||||||
.Setup<Task<HttpResponseMessage>>(
|
|
||||||
"SendAsync",
|
|
||||||
ItExpr.IsAny<HttpRequestMessage>(),
|
|
||||||
ItExpr.IsAny<CancellationToken>()
|
|
||||||
)
|
|
||||||
.ReturnsAsync(responseMessage);
|
|
||||||
|
|
||||||
var formData = new Dictionary<string, string> { { "key", "value" } };
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var response = await _service.FetchAsync("/test", HttpMethod.Post, form: formData);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
|
||||||
_messageHandlerMock.Protected().Verify(
|
|
||||||
"SendAsync",
|
|
||||||
Times.Once(),
|
|
||||||
ItExpr.Is<HttpRequestMessage>(req =>
|
|
||||||
req.Method == HttpMethod.Post &&
|
|
||||||
req.RequestUri == new Uri("https://example.com/test") &&
|
|
||||||
req.Content.Headers.ContentType.MediaType == "application/x-www-form-urlencoded"),
|
|
||||||
ItExpr.IsAny<CancellationToken>()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Test]
|
|
||||||
public async Task FetchAsync_ShouldThrowException_WhenBothBodyAndFormAreSet()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var bodyContent = new StringContent("test body");
|
|
||||||
var formData = new Dictionary<string, string> { { "key", "value" } };
|
|
||||||
|
|
||||||
// Act & Assert
|
|
||||||
Assert.ThrowsAsync<InvalidOperationException>(() => _service.FetchAsync("/test", HttpMethod.Post, body: bodyContent, form: formData));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -17,6 +17,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DigitalData.Core.Client", "
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DigitalData.Core.Abstractions", "DigitalData.Core.Abstractions\DigitalData.Core.Abstractions.csproj", "{13E40DF1-6123-4838-9BF8-086C94E6ADF6}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DigitalData.Core.Abstractions", "DigitalData.Core.Abstractions\DigitalData.Core.Abstractions.csproj", "{13E40DF1-6123-4838-9BF8-086C94E6ADF6}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.Core.ConsoleApp", "DigitalData.Core.ConsoleApp\DigitalData.Core.ConsoleApp.csproj", "{344EEF74-83DD-480A-A1A4-F62E0E3F2102}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -50,6 +52,10 @@ Global
|
|||||||
{13E40DF1-6123-4838-9BF8-086C94E6ADF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{13E40DF1-6123-4838-9BF8-086C94E6ADF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{13E40DF1-6123-4838-9BF8-086C94E6ADF6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{13E40DF1-6123-4838-9BF8-086C94E6ADF6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{13E40DF1-6123-4838-9BF8-086C94E6ADF6}.Release|Any CPU.Build.0 = Release|Any CPU
|
{13E40DF1-6123-4838-9BF8-086C94E6ADF6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{344EEF74-83DD-480A-A1A4-F62E0E3F2102}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{344EEF74-83DD-480A-A1A4-F62E0E3F2102}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{344EEF74-83DD-480A-A1A4-F62E0E3F2102}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{344EEF74-83DD-480A-A1A4-F62E0E3F2102}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
Reference in New Issue
Block a user