Skip to main content

Property/Field Injection

Dependencies can be injected into properties or fields as well. To do so, annotate each property or field that represents a dependency with [Inject].

class ClassA
{
[Inject]
IServiceA serviceA { get; set; }

[Inject]
IServiceB serviceB;

public ClassA()
{
}
}

Injection via properties or fields is a helpful alternative to method injection.

Property/Field Injection with Keys

When you have multiple implementations of the same interface or type registered with different keys, you can use the Key attribute along with Inject to specify which implementation to inject:

class WeaponHolder
{
[Inject, Key(WeaponType.Primary)]
public IWeapon PrimaryWeapon { get; set; }

[Inject, Key("orc")]
public IEnemy OrcEnemy { get; set; }

[Inject, Key(2)]
ILevel nextLevel;
}
note

When using keys with property or field injection, you must use both the Inject and Key attributes. The Key attribute alone is not sufficient for property or field injection.

note

The Key attribute must be used with types that have been registered with the corresponding key using the .Keyed() method. See the Register with Keys section for more information.