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)
|
||||
{
|
||||
var cookieHeader = _cookies.GetCookieHeader(requestUri);
|
||||
requestMessage.Headers.Add("Cookie", cookieHeader);
|
||||
if (!string.IsNullOrWhiteSpace(cookieHeader))
|
||||
{
|
||||
requestMessage.Headers.Add("Cookie", cookieHeader);
|
||||
}
|
||||
}
|
||||
|
||||
// Add body content if provided
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="7.0.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
</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>();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user