你能为 Zenject 提供通用的创建方法吗

Can you have generic create method for Zenject

所以我有一个基础 class 和一些派生的 classes,我想只有一个具有通用创建方法的工厂 将创建适当的实例并注入所有依赖项。这可能使用 Zenject 吗? 有点像。

factory.Create<Archer>()

目前我正在这样做,但如您所见,这不是一个非常干净的解决方案。

 public class CustomFactory : IFactory<Type, BaseUnit>
{
    private DiContainer _container;

    public CustomFactory(DiContainer container)
    {
        _container = container;
    }
    public BaseUnit Create<Type>()
    {
        return null;
    }

    public BaseUnit Create(Type type)
    {
        if (type.BaseType != typeof(BaseUnit))
        {
            Debug.LogError("you cant create objects that are not derrived from base unit");
            return null;
        }

        object obj = _container.Resolve(type) ;
        return _container.InstantiatePrefabForComponent(type, obj as UnityEngine.Object, null, new object[0]) as BaseUnit;
    }
}

我认为您拥有它的方式可能是最简单的方式。以下是您所做的一些小改动:

public class UnitFactory
{
    readonly DiContainer _container;
    readonly List<UnityEngine.Object> _prefabs;

    public UnitFactory(
        List<UnityEngine.Object> prefabs,
        DiContainer container)
    {
        _container = container;
        _prefabs = prefabs;
    }

    public BaseUnit Create<T>()
        where T : BaseUnit
    {
        var prefab = _prefabs.OfType<T>().Single();
        return _container.InstantiatePrefabForComponent<T>(prefab);
    }
}

public class TestInstaller : MonoInstaller<TestInstaller>
{
    public FooUnit FooPrefab;
    public BarUnit BarPrefab;

    public override void InstallBindings()
    {
        Container.Bind<UnitFactory>().AsSingle();
        Container.Bind<UnityEngine.Object>().FromInstance(FooPrefab).WhenInjectedInto<UnitFactory>();
        Container.Bind<UnityEngine.Object>().FromInstance(BarPrefab).WhenInjectedInto<UnitFactory>();
    }
}

这种方法的唯一缺点是预制件不会被验证,因此如果它们缺少注入,直到运行时才会被捕获。另一种方法是为每个 BaseUnit 创建单独的工厂,然后将这些工厂注入 UnitFactory,但这可能会变得混乱