Stashbox.Extensions.DependencyInjection
5.6.0
dotnet add package Stashbox.Extensions.DependencyInjection --version 5.6.0
NuGet\Install-Package Stashbox.Extensions.DependencyInjection -Version 5.6.0
<PackageReference Include="Stashbox.Extensions.DependencyInjection" Version="5.6.0" />
paket add Stashbox.Extensions.DependencyInjection --version 5.6.0
#r "nuget: Stashbox.Extensions.DependencyInjection, 5.6.0"
// Install Stashbox.Extensions.DependencyInjection as a Cake Addin #addin nuget:?package=Stashbox.Extensions.DependencyInjection&version=5.6.0 // Install Stashbox.Extensions.DependencyInjection as a Cake Tool #tool nuget:?package=Stashbox.Extensions.DependencyInjection&version=5.6.0
stashbox-extensions-dependencyinjection
This repository contains Stashbox integrations for ASP.NET Core, .NET Generic Host and simple ServiceCollection based applications.
Package | Version |
---|---|
Stashbox.Extensions.DependencyInjection | |
Stashbox.Extensions.Hosting | |
Stashbox.AspNetCore.Hosting | |
Stashbox.AspNetCore.Multitenant | |
Stashbox.AspNetCore.Testing |
Options turned on by default:
- Automatic tracking and disposal of
IDisposable
andIAsyncDisposable
services. - Lifetime validation for
Developement
environments, but can be extended to all environment types.
Table of Contents
- ASP.NET Core
- .NET Generic Host
- ServiceCollection Based Applications
- Additional IServiceCollection Extensions
- IServiceProvider Extensions
ASP.NET Core
The following example shows how you can integrate Stashbox (with the Stashbox.Extensions.Hosting
package) as the default IServiceProvider
implementation into your ASP.NET Core application:
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseStashbox(container => // Optional configuration options.
{
container.Configure(options => { /*...*/ });
});
builder.Host.ConfigureContainer<IStashboxContainer>((context, container) =>
{
// Execute container validation in development mode.
if (context.HostingEnvironment.IsDevelopment())
container.Validate();
});
Controller / View activation
By default the ASP.NET Core framework uses the DefaultControllerActivator
to instantiate controllers, but it uses the ServiceProvider
only for instantiating their constructor dependencies. This behaviour could hide important errors Stashbox would throw in case of a misconfiguration, so it's recommended to let Stashbox activate your controllers and views.
You can enable this by adding the following options to your service configuration:
// For controllers only.
builder.Services.AddControllers()
.AddControllersAsServices();
// For controllers and views.
builder.Services.AddControllersWithViews()
.AddControllersAsServices()
.AddViewComponentsAsServices();
Multitenant
The Stashbox.AspNetCore.Multitenant
package provides support for multi-tenant applications.
It's responsible for the following tasks:
- Create / maintain the application level Root Container. This container is used to hold the default service registrations for your application.
- Configure / maintain tenant specific child containers. These containers are used to override the default services with tenant specific registrations.
- Tenant identification. Determines the tenant Id based on the current context. To achieve that, you have to provide an
ITenantIdExtractor
implementation.
// The type used to extract the current tenant identifier.
// This implementation shows how to extract the tenant id from a HTTP header.
public class HttpHeaderTenantIdExtractor : ITenantIdExtractor
{
public Task<object> GetTenantIdAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue("TENANT-ID", out var value))
return Task.FromResult<object>(null);
return Task.FromResult<object>(value.First());
}
}
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseStashboxMultitenant<HttpHeaderTenantIdExtractor>(
options => // Multi-tenant configuration options.
{
// The default service registration, it registers into the root container.
// It also could be registered into the default
// service collection with the ConfigureServices() API.
options.RootContainer.Register<IDependency, DefaultDependency>();
// Configure tenants.
options.ConfigureTenant("TenantA", tenant =>
// Register tenant specific service override
tenant.Register<IDependency, TenantASpecificDependency>());
options.ConfigureTenant("TenantB", tenant =>
// Register tenant specific service override
tenant.Register<IDependency, TenantBSpecificDependency>());
});
// The container parameter is the tenant distributor itself.
// Calling its Validate() method will verify the root container and each tenant.
builder.Host.ConfigureContainer<IStashboxContainer>((context, container) =>
{
// Validate the root container and all tenants.
if (context.HostingEnvironment.IsDevelopment())
container.Validate();
});
With this example setup, you can differentiate tenants in a per-request basis identified by a HTTP header, where every tenant gets their overridden services.
Testing
The Stashbox.AspNetCore.Testing
package provides a specialized WebApplicationFactory<T>
based on the Stashbox.AspNetCore.Multitenant
package.
The original WebApplicationFactory<T>
supports the injection of mock services,
but it recreates the hosting application on each WithWebHostBuilder()
call, which - when used heavily - can impact the test execution's performance.
In contrast of WebApplicationFactory<T>
, the StashboxWebApplicationFactory<T>
uses tenant child containers from the Stashbox.AspNetCore.Multitenant
package to distinguish mock services. This solution
doesn't require the recreation of the hosting application for each mocking session.
Let's see a usage example of WebApplicationFactory<T>
:
public class ExampleTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> factory;
public ExampleTests(WebApplicationFactory<Program> factory)
{
this.factory = factory;
}
[Fact]
public async Task Get_Example_Endpoint()
{
var client = this.factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
// service override with mock
services.AddScoped<IDependency, MockDependency>();
});
})
.CreateClient();
var response = await client.GetAsync("/example");
response.EnsureSuccessStatusCode();
Assert.Equal("example body",
await response.Content.ReadAsStringAsync());
}
}
The same functionality with StashboxWebApplicationFactory<T>
would look like this:
public class ExampleTests : IClassFixture<StashboxWebApplicationFactory<Program>>
{
private readonly StashboxWebApplicationFactory<Program> factory;
public ExampleTests(StashboxWebApplicationFactory<Program> factory)
{
this.factory = factory;
}
[Fact]
public async Task Get_Example_Endpoint()
{
var client = this.factory.StashClient((services, httpClientOptions) =>
{
// service override with mock
services.AddScoped<IDependency, MockDependency>();
});
var response = await client.GetAsync("/example");
response.EnsureSuccessStatusCode();
Assert.Equal("example body",
await response.Content.ReadAsStringAsync());
}
}
They look similar, the main difference is how they actually work behind the scenes.
While WebApplicationFactory<Program>
creates a new hosting application upon each WithWebHostBuilder()
call to distinguish mock services from real ones, StashboxWebApplicationFactory<Program>
uses a single host and each StashClient()
call creates a child
Stashbox
container to maintain mock services.
The returning HttpClient
signals the application to use the previously created child container for service resolution.
There's also a difference in their performance:
BenchmarkDotNet=v0.13.4, OS=Windows 10 (10.0.19044.2486/21H2/November2021Update)
AMD Ryzen 9 3900X, 1 CPU, 24 logical and 12 physical cores
.NET SDK=7.0.100
[Host] : .NET 7.0.0 (7.0.22.51805), X64 RyuJIT AVX2
DefaultJob : .NET 7.0.0 (7.0.22.51805), X64 RyuJIT AVX2
| Method | Mean | Error | StdDev | Ratio | Gen0 | Gen1 | Allocated | Alloc Ratio |
|------------------------------------------ |-------------:|-------------:|-------------:|------:|--------:|--------:|----------:|------------:|
| WebApplicationFactory_CreateClient | 22,338.65 us | 2,430.543 us | 7,166.511 us | 1.000 | 93.7500 | 23.4375 | 775.53 KB | 1.000 |
| StashboxWebApplicationFactory_StashClient | 10.10 us | 0.191 us | 0.204 us | 0.001 | 0.5035 | 0.2441 | 4.16 KB | 0.005 |
You can access the underlying tenant container by providing your own tenantId
.
var tenantId = "tenant_id";
var client = this.factory.StashClient((services, httpClientOptions) =>
{
// ...
}, tenantId);
var tenantContainer = this.factory.RootContainer.GetChildContainer(tenantId);
Note: Here you can read more about Stashbox child containers.
.NET Generic Host
The following example adds Stashbox (with the Stashbox.Extensions.Hosting
package) as the default IServiceProvider
implementation into your .NET Generic Host application:
public class Program
{
public static async Task Main(string[] args)
{
var host = Host.CreateDefaultBuilder(args)
.UseStashbox(container => // Optional configuration options.
{
container.Configure(options => { /*...*/ });
})
.ConfigureContainer<IStashboxContainer>((context, container) =>
{
// Execute container validation in development mode.
if (context.HostingEnvironment.IsDevelopment())
container.Validate();
})
.ConfigureServices((context, services) =>
{
services.AddHostedService<Service>();
}).Build();
await host.RunAsync();
}
}
ServiceCollection Based Applications
With the Stashbox.Extensions.Dependencyinjection
package you can replace Microsoft's built-in dependency injection container with Stashbox. This package contains the core functionality used by the Stashbox.Extensions.Hosting
, Stashbox.AspNetCore.Hosting
and Stashbox.AspNetCore.Multitenant
packages.
The following example shows how you can use this integration:
public class Program
{
public static async Task Main(string[] args)
{
// Create the service collection.
var services = new ServiceCollection();
// Configure your service collection.
services.AddLogging();
services.AddOptions();
// Add your services.
services.AddScoped<IService, Service>();
// Integrate Stashbox with the collection and get the ServiceProvider.
var serviceProvider = services.UseStashbox(container => // Optional configuration options.
{
container.Configure(config => config.WithLifetimeValidation());
});
// Start using the application.
using var scope = serviceProvider.CreateScope();
var service = scope.ServiceProvider.GetService<IService>();
await service.DoSomethingAsync();
}
}
Or you can use your own StashboxContainer
to integrate with the ServiceCollection
:
public class Program
{
public static async Task Main(string[] args)
{
// Create your container.
var container = new StashboxContainer(config => // Optional configuration options.
{
config.WithLifetimeValidation();
});
// Create the service collection.
var services = new ServiceCollection();
// Configure your service collection.
services.AddLogging();
services.AddOptions();
// Add your services.
services.AddScoped<IService, Service>();
// Or add them through Stashbox.
container.RegisterScoped<IService, Service>();
// Integrate Stashbox with the collection.
services.UseStashbox(container);
// Execute a dependency tree validation.
container.Validate();
// Start using the application.
await using var scope = container.BeginScope();
var service = scope.Resolve<IService>();
await service.DoSomethingAsync();
}
}
Additional IServiceCollection
Extensions
Most of Stashbox's service registration functionalities are available as extension methods of IServiceCollection
.
-
class Service2 : IService2 { private readonly IService service; public Service2(IService service) { this.service = service; } } var services = new ServiceCollection(); services.AddTransient<IService, Service>(); // Name-less registration. services.AddTransient<IService, AnotherService>("serviceName"); // Register dependency with name. services.AddTransient<IService2, Service2>(config => // Inject the named service as dependency. config.WithDependencyBinding<IService>( "serviceName" // Name of the dependency. ));
Service configuration with Stashbox's Fluent Registration API:
var services = new ServiceCollection(); services.AddTransient<IService, Service>(config => config.WithFactory<IDependency>(dependency => new Service(dependency)).AsImplementedTypes());
-
class ServiceDecorator : IService { private readonly IService decorated; public ServiceDecorator(IService service) { this.decorated = service; } } var services = new ServiceCollection(); services.AddTransient<IService, Service>(); services.Decorate<IService, ServiceDecorator>();
-
var services = new ServiceCollection(); services.ScanAssemblyOf<IService>( // Set a filter for which types should be excluded/included in the registration process. // In this case, only the publicly available types are selected from the assembly. type => type.IsPublic, // The service type selector. Used to filter which interface or base types the implementation should be mapped to. // In this case, we are registering only by interfaces. (implementationType, serviceType) => serviceType.IsInterface, false, // Do not map services to themselves. E.g: Service -> Service. config => { // Register IService instances as scoped. if (config.ServiceType == typeof(IService)) config.WithScopedLifetime(); } );
-
class CompositionRoot : ICompositionRoot { public void Compose(IStashboxContainer container) { container.Register<IService, Service>(); } } var services = new ServiceCollection(); services.ComposeBy<CompositionRoot>(); // Or let Stashbox find all composition roots in an assembly. services.ComposeAssembly(typeof(CompositionRoot).Assembly);
IServiceProvider
Extensions
Named resolution is available on IServiceProvider
through the following extension methods:
GetService<T>(object name)
GetService(Type serviceType, object name)
GetRequiredService<T>(object name)
GetRequiredService(Type serviceType, object name)
GetServices<T>(object name)
GetServices(Type serviceType, object name)
class Service2 : IService2
{
private readonly IService service;
public Service2(IService service)
{
this.service = service;
}
}
var services = new ServiceCollection();
services.AddTransient<IService, Service>(); // Name-less registration.
services.AddTransient<IService, AnotherService>("serviceName"); // Register dependency with name.
var serviceProvider = services.UseStashbox();
var service = serviceProvider.GetRequiredService<IService>(); // type: Service
var anotherService = serviceProvider.GetRequiredService<IService>("serviceName"); // type: AnotherService
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 is compatible. net5.0-windows was computed. net6.0 is compatible. 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 is compatible. 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 is compatible. 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. |
.NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.1 is compatible. |
.NET Framework | net461 is compatible. 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 | tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETFramework 4.6.1
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 6.0.0)
- Stashbox (>= 5.16.0)
-
.NETStandard 2.1
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 3.1.0)
- Stashbox (>= 5.16.0)
-
net5.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 5.0.0)
- Stashbox (>= 5.16.0)
-
net6.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 6.0.0)
- Stashbox (>= 5.16.0)
-
net7.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 7.0.0)
- Stashbox (>= 5.16.0)
-
net8.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Stashbox (>= 5.16.0)
NuGet packages (4)
Showing the top 4 NuGet packages that depend on Stashbox.Extensions.DependencyInjection:
Package | Downloads |
---|---|
Stashbox.Extensions.Hosting
A Microsoft.Extensions.Hosting IHostBuilder extension, which allows Stashbox to be configured as the default service provider. |
|
Stashbox.AspNetCore.Hosting
ASP.NET Core application builder extension which allows Stashbox to be configured as the default service provider. |
|
Stashbox.AspNetCore.Multitenant
ASP.NET Core extension for Stashbox to support multitenant applications. |
|
More.Stashbox.Extensions.DependencyInjection.Keyed
Package Description |
GitHub repositories (3)
Showing the top 3 popular GitHub repositories that depend on Stashbox.Extensions.DependencyInjection:
Repository | Stars |
---|---|
dotnet/runtime
.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
|
|
danielpalme/IocPerformance
Performance comparison of .NET IoC containers
|
|
dotnet/dotnet
Home of .NET's Virtual Monolithic Repository which includes all the code needed to build the .NET SDK from source
|
Version | Downloads | Last updated |
---|---|---|
5.6.0 | 1,841 | 8/21/2024 |
5.5.4 | 1,225 | 7/26/2024 |
5.5.3 | 20,564 | 4/10/2024 |
5.5.2 | 3,402 | 4/8/2024 |
5.5.1 | 335 | 4/2/2024 |
5.5.0 | 10,415 | 12/15/2023 |
5.4.0 | 1,320 | 11/19/2023 |
5.3.0 | 7,667 | 6/21/2023 |
5.2.2 | 2,107 | 6/13/2023 |
5.2.1 | 1,797 | 6/9/2023 |
5.2.0 | 5,265 | 6/5/2023 |
5.1.2 | 1,881 | 6/2/2023 |
5.1.1 | 1,894 | 6/1/2023 |
5.1.0 | 2,850 | 5/31/2023 |
5.0.0 | 1,827 | 5/28/2023 |
4.6.2 | 3,389 | 3/29/2023 |
4.6.1 | 2,019 | 3/29/2023 |
4.6.0 | 31,961 | 2/28/2023 |
4.5.3 | 2,863 | 1/26/2023 |
4.5.2 | 2,194 | 1/26/2023 |
4.5.1 | 2,461 | 1/20/2023 |
4.5.0 | 3,069 | 12/19/2022 |
4.4.0 | 11,511 | 12/6/2022 |
4.3.2 | 2,303 | 11/29/2022 |
4.3.1 | 3,422 | 10/14/2022 |
4.3.0 | 2,933 | 10/12/2022 |
4.2.3 | 13,421 | 9/9/2022 |
4.2.2 | 5,078 | 6/2/2022 |
4.2.1 | 20,468 | 5/16/2022 |
4.2.0 | 3,029 | 5/3/2022 |
4.1.2 | 20,499 | 4/10/2022 |
4.1.1 | 12,146 | 3/12/2022 |
4.1.0 | 2,790 | 3/7/2022 |
4.0.1 | 13,511 | 2/10/2022 |
4.0.0 | 2,743 | 2/9/2022 |
3.2.1 | 3,121 | 1/30/2022 |
3.2.0 | 7,869 | 12/5/2021 |
3.1.1 | 2,299 | 11/22/2021 |
3.1.0 | 2,134 | 11/22/2021 |
3.0.0 | 2,304 | 11/22/2021 |
2.11.4 | 9,549 | 5/26/2021 |
2.11.3 | 3,682 | 3/16/2021 |
2.11.2 | 4,196 | 1/31/2021 |
2.11.1 | 9,781 | 11/16/2020 |
2.11.0 | 2,652 | 11/15/2020 |
2.10.1 | 2,622 | 11/5/2020 |
2.10.0 | 2,602 | 11/2/2020 |
2.9.9 | 2,497 | 11/2/2020 |
2.9.8 | 2,908 | 10/19/2020 |
2.9.7 | 2,457 | 10/16/2020 |
2.9.6 | 2,431 | 10/16/2020 |
2.9.5 | 2,481 | 10/14/2020 |
2.9.4 | 3,308 | 7/21/2020 |
2.9.3 | 94,753 | 7/9/2020 |
2.9.2 | 2,590 | 6/29/2020 |
2.9.1 | 2,899 | 6/22/2020 |
2.9.0 | 2,692 | 6/8/2020 |
2.8.6 | 4,404 | 1/15/2020 |
2.8.5 | 3,120 | 11/11/2019 |
2.8.4 | 2,740 | 10/4/2019 |
2.8.3 | 2,708 | 9/12/2019 |
2.8.1 | 3,085 | 9/11/2019 |
2.7.1 | 2,873 | 6/10/2019 |
2.6.8 | 6,809 | 3/21/2019 |
2.6.7 | 2,992 | 1/13/2019 |
2.6.5 | 2,781 | 12/27/2018 |
2.6.4 | 2,725 | 12/26/2018 |
2.6.3 | 72,269 | 10/24/2018 |
2.6.2 | 3,422 | 7/3/2018 |
2.6.1 | 2,780 | 6/15/2018 |
2.6.0 | 3,060 | 3/20/2018 |
2.5.9 | 2,810 | 2/8/2018 |
2.5.8 | 2,844 | 2/5/2018 |
2.5.7 | 2,771 | 11/24/2017 |
2.5.6 | 2,793 | 11/24/2017 |
2.5.5 | 2,843 | 8/27/2017 |
2.5.4 | 2,745 | 8/7/2017 |
2.5.3 | 2,856 | 6/28/2017 |
2.5.2 | 2,794 | 6/9/2017 |
2.5.1 | 2,768 | 5/18/2017 |
2.4.8 | 2,729 | 5/16/2017 |
2.4.7 | 2,739 | 5/10/2017 |
2.4.6 | 2,778 | 5/10/2017 |
2.4.5 | 2,858 | 5/9/2017 |
2.4.3 | 2,779 | 5/3/2017 |
2.4.1 | 2,902 | 5/3/2017 |
2.3.1 | 2,835 | 3/24/2017 |
2.2.4 | 2,805 | 3/18/2017 |
2.2.3 | 2,721 | 3/17/2017 |
2.2.2 | 2,816 | 3/14/2017 |
2.2.1 | 2,880 | 3/11/2017 |
2.2.0 | 2,870 | 3/2/2017 |
2.1.2 | 2,723 | 2/21/2017 |
2.1.1 | 2,861 | 2/18/2017 |
2.1.0 | 2,738 | 2/18/2017 |
1.0.15 | 2,274 | 2/9/2017 |
1.0.14 | 2,692 | 2/9/2017 |
1.0.13 | 2,358 | 1/27/2017 |
1.0.12 | 3,254 | 1/26/2017 |
1.0.11 | 2,362 | 1/26/2017 |
1.0.10 | 3,258 | 1/26/2017 |
1.0.8 | 2,293 | 1/26/2017 |