Mammoth.Extensions.DependencyInjection 0.5.6

dotnet add package Mammoth.Extensions.DependencyInjection --version 0.5.6
                    
NuGet\Install-Package Mammoth.Extensions.DependencyInjection -Version 0.5.6
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Mammoth.Extensions.DependencyInjection" Version="0.5.6" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Mammoth.Extensions.DependencyInjection" Version="0.5.6" />
                    
Directory.Packages.props
<PackageReference Include="Mammoth.Extensions.DependencyInjection" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Mammoth.Extensions.DependencyInjection --version 0.5.6
                    
#r "nuget: Mammoth.Extensions.DependencyInjection, 0.5.6"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=Mammoth.Extensions.DependencyInjection&version=0.5.6
                    
Install Mammoth.Extensions.DependencyInjection as a Cake Addin
#tool nuget:?package=Mammoth.Extensions.DependencyInjection&version=0.5.6
                    
Install Mammoth.Extensions.DependencyInjection as a Cake Tool

Mammoth.Extensions.DependencyInjection

Build Status

.NET

Introduction

This package offers extensions for the Microsoft.Extensions.DependencyInjection library. It is designed for Microsoft.Extensions.DependencyInjection version 8.0.0 or later, using keyed services introduced in that release.

Installation

dotnet add package Mammoth.Extensions.DependencyInjection

Usage

Decorator

Use the Decorator extension to wrap an existing service with a new implementation without altering the original.

The following example demonstrates how to decorate an existing service with a new implementation.

Limitation

The current implementation requires that the service to be decorated implements an interface.

public interface ITestService { }

public class TestService : ITestService { }

public class DecoratorService1 : ITestService
{
    private readonly ITestService _service;

    public DecoratorService1(ITestService service)
    {
        _service = service;
    }
}

public class DecoratorService2 : ITestService
{
    private readonly ITestService _service;

    public DecoratorService2(ITestService service)
    {
        _service = service;
    }
}
services.AddTransient<ITestService, TestService>();
services.Decorate<IService, DecoratorService1>(); // innermost decorator
services.Decorate<IService, DecoratorService2>(); // outermost decorator

This extension works with Singleton, Scoped, Transient, Keyed, and other service descriptors.

DependsOn (requires Keyed Services support)

Use the DependsOn extensions to register a service that depends on specific instances of other services. For example:

public interface ITestService { }

public class TestService : ITestService { }

public class DependentService
{
    private readonly ITestService _service;

    public DependentService(ITestService service)
    {
        _service = service;
    }
}
services.AddTransient<ITestService, TestService>("one");
services.AddTransient<ITestService, TestService>("two");
services.AddTransient<DependentService>(dependsOn: new Dependency[] {
  Parameter.ForKey("service").Eq("one")
});

Internally, DependsOn creates a factory function to resolve necessary services and build dependent ones.

The current design is limited to some common use case and it's very similar to the one offered by Castle.Windsor, from which we took inspiration:

  • Inject a specific instance of a service that will be resolved:

    services.AddTransient<DependentService>(dependsOn: new Dependency[] {
      Parameter.ForKey("service").Eq("one")
    });
    
  • Inject a value:

    services.AddTransient<DependentService>(dependsOn: new Dependency[] {
      Dependency.OnValue("dep", "val1")
    });
    

This extension works with Singleton, Scoped, Transient, Keyed, and other service descriptors.

Registration Helpers

A set of extension methods provide ways to verify component registrations and manage assemblies for service registration.

ServiceCollection
  • GetServiceDescriptors: returns all the ServiceDescriptors (keyed and non keyed) of a given service type.
  • IsServiceRegistered: checks whether the specified service type is registered in the service collection (keyed or not).
  • IsKeyedServiceRegistered: checks whether the specified service type is registered as keyed in the service collection.
  • IsTransientServiceRegistered: checks whether the specified service type is registered as transient in the service collection.
  • IsScopedServiceRegistered: checks whether the specified service type is registered as scoped in the service collection.
  • IsSingletonServiceRegistered: checks whether the specified service type is registered as singleton in the service collection.
  • IsKeyedTransientServiceRegistered: checks whether the specified service type is registered as transient in the service collection (keyed services).
  • IsKeyedScopedServiceRegistered: checks whether the specified service type is registered as scoped in the service collection (keyed services).
  • IsKeyedSingletonServiceRegistered: checks whether the specified service type is registered as singleton in the service collection (keyed services).
ServiceProvider

To use these extensions, build the ServiceProvider with our custom ServiceProviderFactory. It injects services that track transient disposables and registered service usage.

new HostBuilder().UseServiceProviderFactory(new ServiceProviderFactory(new ExtendedServiceProviderOptions()));

// - or -

var serviceProvider = ServiceProviderFactory.CreateServiceProvider(serviceCollection, new ExtendedServiceProviderOptions());
Detect Incorrect Usage of Transient Disposables

Enable detection of transient disposable services resolved by the root scope:

new HostBuilder().UseServiceProviderFactory(new ServiceProviderFactory(
  new ExtendedServiceProviderOptions 
  {
    DetectIncorrectUsageOfTransientDisposables = true,
    AllowSingletonToResolveTransientDisposables = true,
    ThrowOnOpenGenericTransientDisposable = true,
    DetectIncorrectUsageOfTransientDisposablesExclusionPatterns = ["service", "service2"]
  }));

WARNING: Use this only in debug/development because it relies on reflection and can affect performance. Instead of re-implementing a new ServiceProvider from scratch, this approach modifies each ServiceDescriptor to track resolution context and throw exceptions if required.

Limitations:

  • Open generic transient disposable services cannot be checked, a ServiceDescriptor cannot be created with an Open Generic as ServiceType and an ImplementationFactory (we cannot "rewrite" service registrations), so no error is thrown if they are resolved by the root scope.
  • Open generic resolution context cannot be tracked, a ServiceDescriptor cannot be created with an Open Generic as ServiceType and an ImplementationFactory, so no error is thrown if they are transient and disposable but resolved by the root scope.

Options:

  • AllowSingletonToResolveTransientDisposables: If false, throws when singleton resolves a transient disposable.
  • ThrowOnOpenGenericTransientDisposable: Throws when an open generic transient disposable is registered.
  • DetectIncorrectUsageOfTransientDisposablesExclusionPatterns: list of Regex patterns to exclude services from detection, transient disposable services that match any entry in this list will behave be captured if resolved by the root scope.
IsRegistered extension methods

Additional methods for IServiceProvider:

  • GetAllServices: resolves all keyed and non-keyed services of a given service type.
  • IsServiceRegistered: checks whether the specified service type is registered in the service provider (keyed or non-keyed).
  • IsKeyedServiceRegistered: checks whether the specified service type is registered as keyed in the service provider.
  • IsTransientServiceRegistered: checks whether the specified service type is registered as transient in the service provider (non keyed services).
  • IsScopedServiceRegistered: checks whether the specified service type is registered as scoped in the service provider (non keyed services).
  • IsSingletonServiceRegistered: checks whether the specified service type is registered as singleton in the service provider (non keyed services).
  • IsKeyedTransientServiceRegistered: checks whether the specified service type is registered as transient in the service provider (keyed services).
  • IsKeyedScopedServiceRegistered: checks whether the specified service type is registered as scoped in the service provider (keyed services).
  • IsKeyedSingletonServiceRegistered: checks whether the specified service type is registered as singleton in the service provider (keyed services).
Inspectors

AssemblyInspector inspects assemblies for classes to register.

It is once again inspired by the syntax used in Castle.Windsor to inspect and register services.

It looks for classes and offers a series of methods that are pretty self explanatory to output one or more ServiceDescriptor that will be registered in the ServiceCollection.

It supports DependsOn for keyed services:

serviceCollection.Add(
  new AssemblyInspector()
    .FromAssemblyContaining<ServiceWithKeyedDep>()
    .BasedOn<ServiceWithKeyedDep>()
    .WithServiceSelf()
    .LifestyleSingleton(dependsOn: new Dependency[]
    {
      Parameter.ForKey("keyedService").Eq("one")
    })
);
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.5.6 430 3/26/2025
0.5.6-beta0003 424 3/25/2025
0.5.6-beta0002 428 3/25/2025
0.5.6-beta0001 425 3/25/2025
0.5.5 385 3/24/2025
0.5.4 87 3/21/2025
0.5.3 96 3/21/2025
0.5.2 132 3/20/2025
0.5.2-beta0001 126 3/20/2025
0.5.1 133 3/19/2025
0.5.0 134 3/17/2025
0.4.0 128 3/17/2025
0.4.0-beta0001 124 3/17/2025
0.3.0 104 1/24/2025
0.3.0-beta0004 60 1/24/2025
0.2.0 358 3/6/2024
0.1.3-beta0001 104 3/6/2024
0.1.2 131 3/4/2024
0.1.1 138 3/4/2024
0.1.1-beta0004 106 3/4/2024
0.1.1-beta0003 112 3/4/2024