Method Injection
If you need to inject dependencies into a type but can't do so with constructors, consider using method injection instead. This is most useful for MonoBehaviour
s but can be done with any class, including test cases within the Unity Test Framework.
public class SomeBehaviour : MonoBehaviour
{
float speed;
[Inject]
public void Construct(GameSettings settings)
{
speed = settings.speed;
}
}
The [Inject]
-annotated method can have any name and any accessibility level.
Method Injection with Keys
When you have multiple implementations of the same interface or type registered with different keys, you can use the Key
attribute on method parameters to specify which implementation to inject:
public class WeaponController : MonoBehaviour
{
private IWeapon _primaryWeapon;
private IWeapon _secondaryWeapon;
[Inject]
public void Initialize(
[Key(WeaponType.Primary)] IWeapon primaryWeapon,
[Key(WeaponType.Secondary)] IWeapon secondaryWeapon)
{
_primaryWeapon = primaryWeapon;
_secondaryWeapon = secondaryWeapon;
}
}
The Key
attribute also supports other key types like strings and integers:
public class GameController : MonoBehaviour
{
private IEnemy _enemy;
private ILevel _level;
[Inject]
public void Setup(
[Key("goblin")] IEnemy enemy,
[Key(1)] ILevel level)
{
_enemy = enemy;
_level = level;
}
}
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.
For more information about managing MonoBehaviour
s and GameObject
s, see Injecting into MonoBehaviours.