Demonstrates how to create roots for types that match specific filter criteria, allowing selective exposure of implementations.
using Shouldly;
using Pure.DI;
DI.Setup(nameof(Composition))
.Bind().As(Lifetime.Singleton).To<Configuration>()
.Roots<INotificationService>("My{type}", filter: "*Email*");
var composition = new Composition();
composition.MyEmailService.ShouldBeOfType<EmailService>();
interface IConfiguration;
class Configuration : IConfiguration;
interface INotificationService;
// This service requires an API key which is not bound,
// so it cannot be resolved and should be filtered out.
class SmsService(string apiKey) : INotificationService;
class EmailService(IConfiguration config) : INotificationService;Running this code sample locally
- Make sure you have the .NET SDK 10.0 or later installed
dotnet --list-sdk- Create a net10.0 (or later) console application
dotnet new console -n Sampledotnet add package Pure.DI
dotnet add package Shouldly- Copy the example code into the Program.cs file
You are ready to run the example 🚀
dotnet runNote
Filtering roots provides fine-grained control over which implementations are exposed, useful for conditional feature activation.
The following partial class will be generated:
partial class Composition
{
#if NET9_0_OR_GREATER
private readonly Lock _lock = new Lock();
#else
private readonly Object _lock = new Object();
#endif
private Configuration? _singletonConfiguration62;
public EmailService MyEmailService
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_singletonConfiguration62 is null)
lock (_lock)
if (_singletonConfiguration62 is null)
{
_singletonConfiguration62 = new Configuration();
}
return new EmailService(_singletonConfiguration62);
}
}
}Class diagram:
---
config:
maxTextSize: 2147483647
maxEdges: 2147483647
class:
hideEmptyMembersBox: true
---
classDiagram
Configuration --|> IConfiguration
Composition ..> EmailService : EmailService MyEmailService
EmailService o-- "Singleton" Configuration : IConfiguration
namespace Pure.DI.UsageTests.Basics.RootsWithFilterScenario {
class Composition {
<<partial>>
+EmailService MyEmailService
}
class Configuration {
<<class>>
+Configuration()
}
class EmailService {
<<class>>
+EmailService(IConfiguration config)
}
class IConfiguration {
<<interface>>
}
}