-
Notifications
You must be signed in to change notification settings - Fork 0
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
base: main
Are you sure you want to change the base?
Changes from all commits
8347591
a88afca
36c477b
4785043
66827c3
215e7a1
2504404
dce9982
075bfe7
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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 @@ | ||
[](https://www.nuget.org/packages/BitzArt.DependencyInjection.TransientServiceProvider/) | ||
[](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. | ||
/// </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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
} |
There was a problem hiding this comment.
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.