1.方法注入
根据方法的参数类型,自动申请实例,参数可以有多个。
public class HelloWorldExample : MonoBehaviour
{
private HelloWorldService _helloWorldService;
[Inject]
void Method(HelloWorldService helloWorldService)
{
_helloWorldService = helloWorldService;
}
private void Start()
{
_helloWorldService.HelloWorld();
}
}
2.成员变量注入
成员变量注入发生在构造方法之后。Zenject会遍历所有用[Inject]标记的成员变量,并从容器中查找并返回对应的实例。无论成员变量是私有的还是公共的,都会进行注入。
public class HelloWorldExample : MonoBehaviour
{
[Inject]
private HelloWorldService _helloWorldService;
private void Start()
{
_helloWorldService.HelloWorld();
}
}
3.属性器注入
属性器注入的工作原理与成员变量注入相同,只是把注入的对象换成了属性。
public class HelloWorldExample : MonoBehaviour
{
[Inject] public HelloWorldService HelloWorldService { get; private set; }
private void Start()
{
HelloWorldService.HelloWorld();
}
}
即便set被设置为private也可以正常注入。
4.构造方法注入
构造方法注入是一种特殊的方法注入,可以在对象实例化时注入。
public class HelloWorldService
{
}
public class HelloWorldServiceCaller
{
public HelloWorldServiceCaller(HelloWorldService helloWorldService)
{
Debug.Log(helloWorldService.GetType());
}
}
public class SceneContextExample : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind<HelloWorldService>().AsSingle();
Container.Bind<HelloWorldServiceCaller>().AsSingle();
Container.Resolve<HelloWorldServiceCaller>();
}
}
本文介绍了Unity游戏开发中四种依赖注入的方式:方法注入、成员变量注入、属性器注入和构造方法注入,并通过具体代码示例展示了每种方式的应用场景。
2335

被折叠的 条评论
为什么被折叠?



