Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add transient service provider package #16

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Miscellaneous.sln
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BitzArt.CoreExtensions", "s
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BitzArt.CoreExtensions.Tests", "tests\Misc\BitzArt.CoreExtensions.Tests\BitzArt.CoreExtensions.Tests.csproj", "{039255F7-8BFF-4A5E-ABB6-602AF5F14AA5}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "DependencyInjection", "DependencyInjection", "{BDCAABCC-D420-4A4D-AAC2-3D254D7932CD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BitzArt.DependencyInjection.TransientServiceProvider", "src\DependencyInjection\BitzArt.DependencyInjection.TransientServiceProvider\BitzArt.DependencyInjection.TransientServiceProvider.csproj", "{5F8768B5-FE6F-42DC-9993-F9F4E5AE38E4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -156,6 +160,10 @@ Global
{039255F7-8BFF-4A5E-ABB6-602AF5F14AA5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{039255F7-8BFF-4A5E-ABB6-602AF5F14AA5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{039255F7-8BFF-4A5E-ABB6-602AF5F14AA5}.Release|Any CPU.Build.0 = Release|Any CPU
{5F8768B5-FE6F-42DC-9993-F9F4E5AE38E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5F8768B5-FE6F-42DC-9993-F9F4E5AE38E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5F8768B5-FE6F-42DC-9993-F9F4E5AE38E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5F8768B5-FE6F-42DC-9993-F9F4E5AE38E4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -190,6 +198,8 @@ Global
{A5E6C844-8858-442E-8EAB-2CFD2E59B9EB} = {6C59FADC-BAEA-46B7-A69F-DC2AA0A124D6}
{350EF47C-407B-4509-AE6C-A86F17ED0C80} = {A053045B-CB06-473C-A04E-D54A519B6BBD}
{039255F7-8BFF-4A5E-ABB6-602AF5F14AA5} = {A5E6C844-8858-442E-8EAB-2CFD2E59B9EB}
{BDCAABCC-D420-4A4D-AAC2-3D254D7932CD} = {2638AACB-7314-4962-87BE-93876EEED788}
{5F8768B5-FE6F-42DC-9993-F9F4E5AE38E4} = {BDCAABCC-D420-4A4D-AAC2-3D254D7932CD}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {49BCA0AC-45AF-4DE6-B691-30A0F2959200}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net9.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>BitzArt.DependencyInjection</RootNamespace>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>

<PackageId>BitzArt.DependencyInjection.TransientServiceProvider</PackageId>
<Authors>BitzArt</Authors>
<Description>This package provides isolated transient service providers</Description>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/BitzArt/Miscellaneous</RepositoryUrl>
<PackageProjectUrl>https://github.com/BitzArt/Miscellaneous</PackageProjectUrl>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.2" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
namespace BitzArt.DependencyInjection;

/// <summary>
/// Provides a transient service provider for creating isolated instances of services.
/// </summary>
public interface ITransientServiceProvider : IServiceProvider
{
/// <summary>
/// Get service of type serviceType from the inner <see cref="IServiceProvider"/>.
/// </summary>
/// <param name="serviceType">The type of service to resolve.</param>
/// <returns>The requested service instance or null if not found.</returns>
public new object? GetService(Type serviceType);

/// <summary>
/// Get service of type <typeparamref name="T"/> from the inner <see cref="IServiceProvider"/>.
/// </summary>
/// <typeparam name="T">The type of service object to get.</typeparam>
/// <returns>A service object of type <typeparamref name="T"/> or null if there is no such service.</returns>
public T? GetService<T>();

/// <summary>
/// Get service of type <paramref name="serviceType"/> from the inner <see cref="IServiceProvider"/>.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>A service object of type <paramref name="serviceType"/>.</returns>
public object GetRequiredService(Type serviceType);

/// <summary>
/// Get service of type <typeparamref name="T"/> from the inner <see cref="IServiceProvider"/>.
/// </summary>
/// <typeparam name="T">The type of service object to get.</typeparam>
/// <returns>A service object of type <typeparamref name="T"/>.</returns>
public T GetRequiredService<T>() where T : notnull;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
[![NuGet version](https://img.shields.io/nuget/v/BitzArt.DependencyInjection.TransientServiceProvider.svg)](https://www.nuget.org/packages/BitzArt.DependencyInjection.TransientServiceProvider/)
[![NuGet downloads](https://img.shields.io/nuget/dt/BitzArt.DependencyInjection.TransientServiceProvider.svg)](https://www.nuget.org/packages/BitzArt.DependencyInjection.TransientServiceProvider/)

# Overview

`BitzArt.DependencyInjection.TransientServiceProvider` is a NuGet package that enables the creation and management of transient service providers within a dependency injection container.

It allows resolving services within isolated transient scopes while supporting both named and unnamed providers. This ensures proper service lifetime management without polluting the root provider.

> ⚠️
> Currently, the library requires .NET 9 and is not compatible with earlier versions. Ensure your project targets .NET 9 or later to use this package.

## How it Works

### Centralized Provider Factory:

The package introduces a factory that holds a reference to the root service provider and a delegate function to create transient providers.

### Named and Unnamed Providers:

- Named Providers: Uses a thread-safe cache (a concurrent dictionary) to store and retrieve providers by name. If a provider for a given name doesn’t exist, it is created, cached, and then returned.
- Unnamed Providers: Always creates a new transient provider instance using the delegate function.

### Thread Safety:

The factory employs locking mechanisms to ensure that the creation and caching of named providers occur safely when accessed concurrently.

### Isolation and Flexibility:

This approach allows different parts of an application to obtain isolated service provider instances, ensuring that transient services do not interfere with one another.


## Usage

The following demonstrates how to configure and use the `TransientServiceProvider`.

### Here's How to Configure It

Below is an example of how to set up the `TransientServiceProvider` within your application's service registration:

```csharp
services.AddTransientServiceProvider(sp =>
{
// Set up a fresh service collection for registration.
var services = new ServiceCollection();

// Add services, database contexts, or other dependencies here.

// Construct a service provider from the configured collection.
var innerServiceProvider = services.BuildServiceProvider();

// Optionally, utilize the newly created provider if needed.

// Provide a new TransientServiceProvider instance with the inner provider.
return new TransientServiceProvider(innerServiceProvider);
});
```

### Here's How to Use It

Once the `TransientServiceProviderFactory` is configured, you can inject it into your classes and call `GetProvider()` to create isolated service providers as needed. Here’s an example:

```csharp
public class SomeClass(TransientServiceProviderFactory factory)
{
public async Task SomeMethod()
{
// Get an isolated service provider
using var serviceProvider = factory.GetProvider();

// Resolve the service
var service = serviceProvider.GetRequiredService<SomeService>();

// Call the service method
await service.SomeServiceMethod();
}
}
```

You can also create or retrieve named isolated service providers by calling GetProvider("some-name"). If a provider with that name already exists, it will return the existing instance rather than creating a new one. Here’s an example:

```csharp
public class AnotherClass(TransientServiceProviderFactory factory)
{
public async Task AnotherMethod()
{
// Get or reuse a named isolated service provider
using var namedProvider = factory.GetProvider("MyNamedProvider");

// Resolve the service from the named provider
var service = namedProvider.GetRequiredService<SomeService>();

// Call the service method
await service.SomeServiceMethod();
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Microsoft.Extensions.DependencyInjection;

namespace BitzArt.DependencyInjection;

/// <summary>
/// Provides DI container extensions.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Registers the factory as a singleton and adds a transient registration that retrieves a provider from the factory.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it necessary for the package's user to know how exactly the factory and the providers are registered under the hood (singleton / transient, etc.)?

I believe this could use additional explanation on how the factory and the providers are connected. Consider adding something like the following:

/// Registers an <see cref="TransientServiceProviderFactory"/>

and referring to the TransientServiceProvider somewhere in a similar fashion.

This could give the reader a way to figure out more about each of these classes by clicking their respective links in the summary here.

/// </summary>
public static IServiceCollection AddTransientServiceProvider(
this IServiceCollection services,
Func<IServiceProvider, ITransientServiceProvider> build)
{
services.AddSingleton(sp => new TransientServiceProviderFactory(sp, build));

services.AddTransient(x =>
{
var factory = x.GetRequiredService<TransientServiceProviderFactory>();
var provider = factory.GetProvider();
return provider;
});

return services;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using Microsoft.Extensions.DependencyInjection;

namespace BitzArt.DependencyInjection;

/// <summary>
/// Provides a transient service provider for creating isolated instances of services that delegates service resolution
/// to an inner <see cref="IServiceProvider"/>.
/// </summary>
public class TransientServiceProvider(IServiceProvider innerServiceProvider) : ITransientServiceProvider
{
private readonly IServiceProvider _innerServiceProvider = innerServiceProvider;

/// <inheritdoc/>
public object? GetService(Type serviceType)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe just inheritdoc?

Also, I believe this could use the following form:

object? IServiceProvider.GetService(Type serviceType)

for additional clarity regarding what this does and why it is here

{
return _innerServiceProvider.GetService(serviceType);
}

/// <inheritdoc/>
public T? GetService<T>()
{
return (T?)GetService(typeof(T));
}

/// <inheritdoc/>
public object GetRequiredService(Type serviceType)
{
return _innerServiceProvider.GetRequiredService(serviceType);
}

/// <inheritdoc/>
public T GetRequiredService<T>() where T : notnull
{
return (T)GetRequiredService(typeof(T));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System.Collections.Concurrent;

namespace BitzArt.DependencyInjection;

/// <summary>
/// Factory for creating and managing transient service providers.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does not seem like this brings anything new to the table, while this class could use some explanation

/// </summary>
/// <param name="serviceProvider">The root service provider.</param>
/// <param name="build">A function to create a new <see cref="ITransientServiceProvider"/>.</param>
public class TransientServiceProviderFactory(
IServiceProvider serviceProvider,
Func<IServiceProvider, ITransientServiceProvider> build)
{
private readonly ConcurrentDictionary<string, ITransientServiceProvider> _namedProviders = [];

private readonly Lock _lock = new();

private readonly Func<IServiceProvider, ITransientServiceProvider> _build = build;

/// <summary>
/// Returns a transient service provider associated with the given name,
/// creating and caching a new instance if not already present.
/// </summary>
/// <param name="name">The identifier for the provider instance.</param>
/// <returns>A <see cref="ITransientServiceProvider"/> instance.</returns>
public ITransientServiceProvider GetProvider(string name)
{
ITransientServiceProvider? provider;

if (!_namedProviders.TryGetValue(name, out provider))
{
lock (_lock)
{
if (!_namedProviders.TryGetValue(name, out provider))
{
provider = _build(serviceProvider);
_namedProviders[name] = provider;
}
}
}

return provider;
}

/// <summary>
/// Creates and returns a new transient service provider instance.
/// </summary>
/// <returns>A new <see cref="ITransientServiceProvider"/> instance.</returns>
public ITransientServiceProvider GetProvider() => _build(serviceProvider);
}