Composition roots from other assemblies or projects can be used as a source of bindings. When you add a binding to a composition from another assembly or project, the roots of the composition with the RootKind.Exposed type will be used in the bindings automatically. For example, in some assembly a composition is defined as:
public partial class CompositionWithGenericRootsAndArgsInOtherProject
{
private static void Setup() =>
DI.Setup()
.Hint(Hint.Resolve, "Off")
.RootArg<int>("id")
.Bind().As(Lifetime.Singleton).To<MyDependency>()
.Bind().To<MyGenericService<TT>>()
.Root<IMyGenericService<TT>>("GetMyService", kind: RootKinds.Exposed);
}using Shouldly;
using Pure.DI;
using static Pure.DI.Lifetime;
using OtherAssembly;
DI.Setup(nameof(Composition))
.RootArg<int>("id")
// Binds to exposed composition roots from other project
.Bind().As(Singleton).To<CompositionWithGenericRootsAndArgsInOtherProject>()
.Root<Program>("GetProgram");
var composition = new Composition();
var program = composition.GetProgram(33);
program.DoSomething(99);
partial class Program(IMyGenericService<int> myService)
{
public void DoSomething(int value) => myService.DoSomething(value);
}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 runImportant
At this point, a composition from another assembly or another project can be used for this purpose. Compositions from the current project cannot be used in this way due to limitations of the source code generators.
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 OtherAssembly.CompositionWithGenericRootsAndArgsInOtherProject? _singletonCompositionWithGenericRootsAndArgsInOtherProject63;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Program GetProgram(int id)
{
OtherAssembly.IMyGenericService<int> transientIMyGenericService40;
int localId = id;
if (_singletonCompositionWithGenericRootsAndArgsInOtherProject63 is null)
lock (_lock)
if (_singletonCompositionWithGenericRootsAndArgsInOtherProject63 is null)
{
_singletonCompositionWithGenericRootsAndArgsInOtherProject63 = new OtherAssembly.CompositionWithGenericRootsAndArgsInOtherProject();
}
OtherAssembly.CompositionWithGenericRootsAndArgsInOtherProject localInstance_1182D1271 = _singletonCompositionWithGenericRootsAndArgsInOtherProject63;
transientIMyGenericService40 = localInstance_1182D1271.GetMyService<int>(localId);
return new Program(transientIMyGenericService40);
}
}