Func helps when the logic must enter instances of some type on demand or more than once. This is a very handy mechanism for instance replication. For example it is used when implementing the Lazy<T>
injection.
using Shouldly;
using Pure.DI;
using System.Collections.Immutable;
DI.Setup(nameof(Composition))
.Bind().To<Dependency>()
.Bind().To<Service>()
// Composition root
.Root<IService>("Root");
var composition = new Composition();
var service = composition.Root;
service.Dependencies.Length.ShouldBe(3);
interface IDependency;
class Dependency : IDependency;
interface IService
{
ImmutableArray<IDependency> Dependencies { get; }
}
class Service(Func<IDependency> dependencyFactory): IService
{
public ImmutableArray<IDependency> Dependencies =>
[
dependencyFactory(),
dependencyFactory(),
dependencyFactory()
];
}
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
Be careful, replication takes into account the lifetime of the object.
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
{
Func<IDependency> perBlockFunc1 = new Func<IDependency>(
[MethodImpl(MethodImplOptions.AggressiveInlining)]
() =>
{
IDependency localValue103 = new Dependency();
return localValue103;
});
return new Service(perBlockFunc1);
}
}
}
Class diagram:
---
config:
class:
hideEmptyMembersBox: true
---
classDiagram
Dependency --|> IDependency
Service --|> IService
Composition ..> Service : IService Root
Service o-- "PerBlock" FuncᐸIDependencyᐳ : FuncᐸIDependencyᐳ
FuncᐸIDependencyᐳ *-- Dependency : IDependency
namespace Pure.DI.UsageTests.BCL.FuncScenario {
class Composition {
<<partial>>
+IService Root
}
class Dependency {
+Dependency()
}
class IDependency {
<<interface>>
}
class IService {
<<interface>>
}
class Service {
+Service(FuncᐸIDependencyᐳ dependencyFactory)
}
}
namespace System {
class FuncᐸIDependencyᐳ {
<<delegate>>
}
}