Skip to content

Latest commit

 

History

History
93 lines (75 loc) · 2.58 KB

exposed-roots-via-root-arg.md

File metadata and controls

93 lines (75 loc) · 2.58 KB

Exposed roots via root arg

CSharp

Composition roots from other assemblies or projects can be used as a source of bindings passed through root arguments. 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 CompositionInOtherProject
{
    private static void Setup() =>
        DI.Setup()
            .Bind().As(Lifetime.Singleton).To<MyDependency>()
            .Bind().To<MyService>()
            .Root<IMyService>("MyService", kind: RootKinds.Exposed);
}
using Pure.DI;
using OtherAssembly;

DI.Setup(nameof(Composition))
    .Hint(Hint.Resolve, "Off")
    // Binds to exposed composition roots from other project
    .RootArg<CompositionInOtherProject>("baseComposition")
    .Root<Program>("GetProgram");

var baseComposition = new CompositionInOtherProject();
var composition = new Composition();
var program = composition.GetProgram(baseComposition);
program.DoSomething();

partial class Program(IMyService myService)
{
    public void DoSomething() => myService.DoSomething();
}
Running this code sample locally
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(128)]
  public Composition()
  {
    _root = this;
  }

  internal Composition(Composition parentScope)
  {
    _root = (parentScope ?? throw new ArgumentNullException(nameof(parentScope)))._root;
  }

  [MethodImpl(MethodImplOptions.AggressiveInlining)]
  public Program GetProgram(OtherAssembly.CompositionInOtherProject baseComposition)
  {
    OtherAssembly.IMyService transientIMyService1;
    OtherAssembly.CompositionInOtherProject localInstance_1182D1277 = baseComposition;
    transientIMyService1 = localInstance_1182D1277.MyService;
    return new Program(transientIMyService1);
  }
}