using Pure.DI;
DI.Setup(nameof(Composition))
.Bind<IDependency>().To<Dependency>()
.Bind<IService>().To<Service>()
// Composition root
.Root<IService>("Root");
var composition = new Composition();
var service = composition.Root;
interface IDependency;
class Dependency : IDependency;
interface IService;
class Service(WeakReference<IDependency> dependency) : IService
{
public IDependency? Dependency =>
dependency.TryGetTarget(out var value)
? value
: null;
}
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
- Add reference to NuGet package
dotnet add package Pure.DI
- 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
{
return new Service(new WeakReference<IDependency>(new Dependency()));
}
}
}
Class diagram:
---
config:
class:
hideEmptyMembersBox: true
---
classDiagram
Dependency --|> IDependency
Service --|> IService
Composition ..> Service : IService Root
Service *-- WeakReferenceᐸIDependencyᐳ : WeakReferenceᐸIDependencyᐳ
WeakReferenceᐸIDependencyᐳ *-- Dependency : IDependency
namespace Pure.DI.UsageTests.BCL.WeakReferenceScenario {
class Composition {
<<partial>>
+IService Root
}
class Dependency {
+Dependency()
}
class IDependency {
<<interface>>
}
class IService {
<<interface>>
}
class Service {
+Service(WeakReferenceᐸIDependencyᐳ dependency)
}
}
namespace System {
class WeakReferenceᐸIDependencyᐳ {
+WeakReference(IDependency target)
}
}