Specifying IEnumerable<T>
as the injection type allows you to inject instances of all bindings that implement type T
in a lazy fashion - the instances will be provided one by one, in order corresponding to the sequence of bindings.
using Shouldly;
using Pure.DI;
using System.Collections.Immutable;
DI.Setup(nameof(Composition))
.Bind<IDependency>().To<AbcDependency>()
.Bind<IDependency>(2).To<XyzDependency>()
.Bind<IService>().To<Service>()
// Composition root
.Root<IService>("Root");
var composition = new Composition();
var service = composition.Root;
service.Dependencies.Length.ShouldBe(2);
service.Dependencies[0].ShouldBeOfType<AbcDependency>();
service.Dependencies[1].ShouldBeOfType<XyzDependency>();
interface IDependency;
class AbcDependency : IDependency;
class XyzDependency : IDependency;
interface IService
{
ImmutableArray<IDependency> Dependencies { get; }
}
class Service(IEnumerable<IDependency> dependencies) : IService
{
public ImmutableArray<IDependency> Dependencies { get; }
= [..dependencies];
}
Running this code sample locally
- Make sure you have the .NET SDK 9.0 or later is installed
dotnet --list-sdk
- Create a net9.0 (or later) console application
dotnet new console -n Sample
dotnet 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 run
The following partial class will be generated:
partial class Composition
{
private readonly Composition _root;
[OrdinalAttribute(256)]
public Composition()
{
_root = this;
}
internal Composition(Composition parentScope)
{
_root = (parentScope ?? throw new ArgumentNullException(nameof(parentScope)))._root;
}
public IService Root
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
IEnumerable<IDependency> EnumerationOf_perBlockIEnumerable1()
{
yield return new AbcDependency();
yield return new XyzDependency();
}
IEnumerable<IDependency> perBlockIEnumerable1 = EnumerationOf_perBlockIEnumerable1();
return new Service(perBlockIEnumerable1);
}
}
}
Class diagram:
---
config:
class:
hideEmptyMembersBox: true
---
classDiagram
AbcDependency --|> IDependency
XyzDependency --|> IDependency : 2
Service --|> IService
Composition ..> Service : IService Root
Service o-- "PerBlock" IEnumerableᐸIDependencyᐳ : IEnumerableᐸIDependencyᐳ
IEnumerableᐸIDependencyᐳ *-- AbcDependency : IDependency
IEnumerableᐸIDependencyᐳ *-- XyzDependency : 2 IDependency
namespace Pure.DI.UsageTests.BCL.EnumerableScenario {
class AbcDependency {
+AbcDependency()
}
class Composition {
<<partial>>
+IService Root
}
class IDependency {
<<interface>>
}
class IService {
<<interface>>
}
class Service {
+Service(IEnumerableᐸIDependencyᐳ dependencies)
}
class XyzDependency {
+XyzDependency()
}
}
namespace System.Collections.Generic {
class IEnumerableᐸIDependencyᐳ {
<<interface>>
}
}