Skip to content

Latest commit

 

History

History
140 lines (119 loc) · 3 KB

generic-injections-as-required.md

File metadata and controls

140 lines (119 loc) · 3 KB

Generic injections as required

using Shouldly;
using Pure.DI;
using System.Collections.Generic;

DI.Setup(nameof(Composition))
    .Bind().To<Dependency<TT>>()
    .Bind().To<Service<TT>>()

    // Composition root
    .Root<IService<int>>("Root");

var composition = new Composition();
var service = composition.Root;
service.Dependencies.Count.ShouldBe(2);

interface IDependency<T>;

class Dependency<T> : IDependency<T>;

interface IService<T>
{
    IReadOnlyList<IDependency<T>> Dependencies { get; }
}

class Service<T>(Func<IDependency<T>> dependencyFactory): IService<T>
{
    public IReadOnlyList<IDependency<T>> Dependencies { get; } =
    [
        dependencyFactory(),
        dependencyFactory()
    ];
}
Running this code sample locally
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;

  [OrdinalAttribute(256)]
  public Composition()
  {
    _root = this;
  }

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

  public IService<int> Root
  {
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    get
    {
      Func<IDependency<int>> perBlockFunc1 = new Func<IDependency<int>>(
      [MethodImpl(MethodImplOptions.AggressiveInlining)]
      () =>
      {
        IDependency<int> localValue141 = new Dependency<int>();
        return localValue141;
      });
      return new Service<int>(perBlockFunc1);
    }
  }
}

Class diagram:

---
 config:
  class:
   hideEmptyMembersBox: true
---
classDiagram
	ServiceᐸInt32ᐳ --|> IServiceᐸInt32ᐳ
	DependencyᐸInt32ᐳ --|> IDependencyᐸInt32ᐳ
	Composition ..> ServiceᐸInt32ᐳ : IServiceᐸInt32ᐳ Root
	ServiceᐸInt32ᐳ o-- "PerBlock" FuncᐸIDependencyᐸInt32ᐳᐳ : FuncᐸIDependencyᐸInt32ᐳᐳ
	FuncᐸIDependencyᐸInt32ᐳᐳ *--  DependencyᐸInt32ᐳ : IDependencyᐸInt32ᐳ
	namespace Pure.DI.UsageTests.Generics.GenericInjectionsAsRequiredScenario {
		class Composition {
		<<partial>>
		+IServiceᐸInt32ᐳ Root
		}
		class DependencyᐸInt32ᐳ {
			+Dependency()
		}
		class IDependencyᐸInt32ᐳ {
			<<interface>>
		}
		class IServiceᐸInt32ᐳ {
			<<interface>>
		}
		class ServiceᐸInt32ᐳ {
			+Service(FuncᐸIDependencyᐸInt32ᐳᐳ dependencyFactory)
		}
	}
	namespace System {
		class FuncᐸIDependencyᐸInt32ᐳᐳ {
				<<delegate>>
		}
	}
Loading