你能拥有Zenject的通用创建方法吗?

时间:2018-04-28 04:45:30

标签: c# unity3d dependency-injection zenject

所以我有一个基类和一些派生类,我想只有一个带有通用创建方法的工厂,它将创建适当的实例并注入所有依赖项。这可能使用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;
    }
}

1 个答案:

答案 0 :(得分:1)

我认为你拥有它的方式可能是最简单的方法。以下是对您所做的一些细微更改:

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,但这可能会变得混乱