Demo:
using UnityEngine;
using Zenject;
public class TestConditionalBindingInstaller : MonoInstaller
{
public override void InstallBindings()
{
//Int默认注入为5
Container.Bind<int>().FromInstance(5);
//ConditionalA中的Int注入为10
Container.Bind<int>().FromInstance(10).When(context => context.ObjectType==typeof(ConditionalA));
//ConditionalB中的Int注入为20
Container.Bind<int>().FromInstance(20).WhenInjectedInto<ConditionalB>();
//实例化的conditionalC01注入int为30
Container.Bind<int>().FromInstance(30).When(context => context.ObjectInstance==conditionalC01);
}
ConditionalC conditionalC01=new ConditionalC();
public void Start()
{
ConditionalA conditionalA=new ConditionalA();
ConditionalB conditionalB=new ConditionalB();
ConditionalC conditionalC02=new ConditionalC();
//注入
Container.Inject(conditionalA);
Container.Inject(conditionalB);
Container.Inject(conditionalC01);
Container.Inject(conditionalC02);
//调试
Debug.LogFormat("注入ConditianalA中的Int数值,猜测为10,实际为{0};注入ConditianalB中的Int数值,猜测为20,实际为{1};",conditionalA.Number,conditionalB.Number);
Debug.LogFormat("注入conditionalC01中的Int数值,猜测为30,实际为{0};注入conditionalC02中的Int数值,猜测为5,实际为是{1};",conditionalC01.Number,conditionalC02.Number);
}
}
public class ConditionalA
{
[Inject] public int Number;
}
public class ConditionalB
{
[Inject] public int Number;
}
public class ConditionalC
{
[Inject] public int Number;
}
运行结果: 和猜测一个样