Sometimes you need roots for all types inherited from available at compile time at the point where the method is called.
using Shouldly;
using Pure.DI;
DI.Setup(nameof(Composition))
.Bind().As(Lifetime.Singleton).To<Dependency>()
.Roots<IService>("My{type}");
var composition = new Composition();
composition.MyService1.ShouldBeOfType<Service1>();
composition.MyService2.ShouldBeOfType<Service2>();
interface IDependency;
class Dependency : IDependency;
interface IService;
class Service1(IDependency dependency) : IService;
class Service2(IDependency dependency) : IService;
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;
private readonly Lock _lock;
private Dependency? _singletonDependency43;
[OrdinalAttribute(256)]
public Composition()
{
_root = this;
_lock = new Lock();
}
internal Composition(Composition parentScope)
{
_root = (parentScope ?? throw new ArgumentNullException(nameof(parentScope)))._root;
_lock = _root._lock;
}
public Service2 MyService2
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_root._singletonDependency43 is null)
{
using (_lock.EnterScope())
{
if (_root._singletonDependency43 is null)
{
_root._singletonDependency43 = new Dependency();
}
}
}
return new Service2(_root._singletonDependency43);
}
}
public Service1 MyService1
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_root._singletonDependency43 is null)
{
using (_lock.EnterScope())
{
if (_root._singletonDependency43 is null)
{
_root._singletonDependency43 = new Dependency();
}
}
}
return new Service1(_root._singletonDependency43);
}
}
}
Class diagram:
---
config:
class:
hideEmptyMembersBox: true
---
classDiagram
Dependency --|> IDependency
Composition ..> Service2 : Service2 MyService2
Composition ..> Service1 : Service1 MyService1
Service2 o-- "Singleton" Dependency : IDependency
Service1 o-- "Singleton" Dependency : IDependency
namespace Pure.DI.UsageTests.Basics.RootsScenario {
class Composition {
<<partial>>
+Service1 MyService1
+Service2 MyService2
}
class Dependency {
+Dependency()
}
class IDependency {
<<interface>>
}
class Service1 {
}
class Service2 {
}
}