3

我的 Unity 项目在不同的 asmdef 程序集定义中分为一个核心项目和几个模块。每个模块都有一个对 Core 的程序集引用。

我的核心安装程序看起来像:

    public class CoreInstaller : MonoInstaller
    {
        [SerializeField] private GameObject ShipPrefab;

        public override void InstallBindings()
        {
            Container.BindInterfacesTo<GameRunner>().AsSingle();
            Container.BindFactory<Ship, Ship.Factory>().FromSubContainerResolve().ByNewPrefabInstaller<ShipInstaller>(ShipPrefab);
        }
    }

如您所见,我使用 Zenject DI 将 a 绑定Ship到 a Ship.Factory,使用 theShipInstaller绑定对船的子容器的依赖项。

问题是可以绑定存在于程序集中但不在任何模块中ShipInstaller的依赖项。Core

我已经设法通过创建一个IShipInstaller接口来解决这个问题,该接口Core可以由其他模块中的安装程序实现,以便在创建 Ship 对象时向其注入额外的依赖项。其他模块有他们自己的安装程序,然后可以将他们的船舶安装程序绑定到该接口,并且它们都在运行时作为列表注入到船舶中。

例如


    public class OptionalShipInstaller : IShipInstaller
    {
        public void InstallBindings(DiContainer subContainer)
        {
            subContainer.BindInterfacesTo<OptionalShipDependency>().AsSingle();
        }
    }

    public class ModuleInstaller: MonoInstaller
    {
        public override void InstallBindings()
        {
            Container.BindInterfacesTo<OptionalShipInstaller>().AsSingle();
        }
    }
    public class ShipInstaller : Installer<ShipInstaller>
    {
        [Inject] private IEnumerable<IShipInstaller> _subContainerInstallers;

        public override void InstallBindings()
        {
            Container.BindInterfacesTo<CoreShipDependency>().AsSingle();
            foreach (var subContainerInstaller in _subContainerInstallers)
            {
                subContainerInstaller.InstallBindings(Container);
            }
        }
    }

这行得通,但这样做的问题是它无法通过 Zenject 验证,因为在验证期间我相信它让Container.Resolve方法只返回一个默认值(null 或空列表)。

根据文档,安装程序可以运行另一个安装程序,Installer.Install(Container)例如我的 OptionalShipInstaller应该如下所示:


    public class OptionalShipInstaller : Installer<OptionalShipInstaller>
    {
        public override void InstallBindings()
        {
            Container.BindInterfacesTo<OptionalShipDependency>().AsSingle();
        }
    }
    

并且ShipInstaller应该像这样运行静态安装方法:


    public class ShipInstaller : Installer<ShipInstaller>
    {
        public override void InstallBindings()
        {
            Container.BindInterfacesTo<CoreShipDependency>().AsSingle();
            OptionalShipInstaller.Install(Container);
        }
    }

但是,它OptionalShipInstaller是不可见的,ShipInstaller因为它存在于一个未在其中引用的单独程序集中Core- 模块依赖于核心,而不是相反!

所以基本上,我有没有办法在绑定后将另一个安装程序附加到船舶工厂?或者我可以解决此问题的任何其他方法将不胜感激。

4

0 回答 0