Skip to content

Latest commit

 

History

History
97 lines (79 loc) · 2.67 KB

exposed-roots-via-arg.md

File metadata and controls

97 lines (79 loc) · 2.67 KB

Exposed roots via arg

Composition roots from other assemblies or projects can be used as a source of bindings passed through class 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))
    // Binds to exposed composition roots from other project
    .Arg<CompositionInOtherProject>("baseComposition")
    .Root<Program>("Program");

var baseComposition = new CompositionInOtherProject();
var composition = new Composition(baseComposition);
var program = composition.Program;
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;

  private readonly OtherAssembly.CompositionInOtherProject _argBaseComposition;

  [OrdinalAttribute(128)]
  public Composition(OtherAssembly.CompositionInOtherProject baseComposition)
  {
    _argBaseComposition = baseComposition ?? throw new ArgumentNullException(nameof(baseComposition));
    _root = this;
  }

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

  public Program Program
  {
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    get
    {
      OtherAssembly.IMyService transientIMyService1;
      OtherAssembly.CompositionInOtherProject localInstance_1182D12745 = _argBaseComposition;
      transientIMyService1 = localInstance_1182D12745.MyService;
      return new Program(transientIMyService1);
    }
  }
}