inject-attribute.md

July 3, 2026 ยท View on GitHub

Inject attribute

If you want attributes without defining your own, add this package:

NuGet

It provides Inject and Inject<T> for constructors, methods, properties, and fields, letting you configure injection metadata.

using Shouldly;
using Pure.DI.Abstractions;
using Pure.DI;

DI.Setup(nameof(PersonComposition))
    .Arg<int>("personId")
    .Bind<Uri>("Person Uri").To(() => new Uri("https://github.com/DevTeam/Pure.DI"))
    .Bind("NikName").To(() => "Nik")
    .Bind().To<Person>()

    // Composition root
    .Root<IPerson>("Person");

var composition = new PersonComposition(personId: 123);
var person = composition.Person;
person.ToString().ShouldBe("123 Nik https://github.com/DevTeam/Pure.DI");

interface IPerson;

class Person([Inject("NikName")] string name) : IPerson
{
    private object? _state;

    [Inject<int>] internal object Id = "";

    public void Initialize([Inject<Uri>("Person Uri", 1)] object state) =>
        _state = state;

    public override string ToString() => $"{Id} {name} {_state}";
}
Running this code sample locally
dotnet --list-sdk
  • Create a net10.0 (or later) console application
dotnet new console -n Sample
dotnet add package Pure.DI
dotnet add package Shouldly
dotnet add package Pure.DI.Abstractions
  • Copy the example code into the Program.cs file

You are ready to run the example ๐Ÿš€

dotnet run

This package should also be included in a project:

NuGet

The following partial class will be generated
partial class PersonComposition
{
  private readonly int _argPersonId;

  [OrdinalAttribute(128)]
  public PersonComposition(int personId)
  {
    _argPersonId = personId;
  }

  public IPerson Person
  {
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    get
    {
      string transientString = "Nik";
      Uri transientUri = new Uri("https://github.com/DevTeam/Pure.DI");
      var transientPerson = new Person(transientString);
      transientPerson.Id = _argPersonId;
      transientPerson.Initialize(transientUri);
      return transientPerson;
    }
  }
}

Class diagram:

---
 config:
  class:
   hideEmptyMembersBox: true
---
classDiagram
	Person --|> IPerson
	PersonComposition ..> Person : IPerson Person
	Person o-- Int32 : Argument "personId"
	Person *-- Uri : "Person Uri" Uri
	Person *-- String : "NikName" String
	namespace Pure.DI.UsageTests.Attributes.InjectAttributeScenario {
		class IPerson {
			<<interface>>
		}
		class Person {
				<<class>>
			+Person(String name)
			~Object Id
			+Initialize(Object state) : Void
		}
		class PersonComposition {
		<<partial>>
		+IPerson Person
		}
	}
	namespace System {
		class Int32 {
				<<struct>>
		}
		class String {
				<<class>>
		}
		class Uri {
				<<class>>
		}
	}

See also: