Zenject: Initier

yoonsang lee·2022년 5월 29일
0

SceneContext

  • the Entry Point (Composition Root) at which you need to provide all bindings to automate DI
  • to add content to the scene, you need to write what is referred to as Installer, which declares all the dependencies and their relationships with each other.
  • All dependencies that are maked as NonLazy are automatically created after the installers run.

Injection

  1. Constructor Injection
public class Foo {
    IBar _bar;

    public Foo(IBar bar) {
        _bar = bar;
    }
}
  1. Field Injection
public class Foo {
	[Inject]
    IBar _bar;
}

it occurs after ctor is called.
fields can be either private or public

  1. Property Injection
public class Foo {
    [Inject]
    public IBar Bar {
        get;
        private set;
    }
}
  1. Method Injection
public class Foo {
    IBar _bar;
    Qux _qux;

    [Inject]
    public void Init(IBar bar, Qux qux) {
        _bar = bar;
        _qux = qux;
    }
}

Using in Unity

  1. Inject methods are the recommended approach for MonoBehaviours, since MonoBehaviours cannot have constructors.

  2. Do not use inject methods for initialization logic. prefer IInitializable.Initialize or Start() methods instead, since this will allow the entire initial object graph to be created first.

Recommendations

Best practice is to prefer ctor/method injection compared to field/property injection.

  1. Prefer Constructor to initialize as always as it is always guaranteed to be called once before all.

  2. Ctor injection guarantees no circular dependency, Zenject allows the circular dependency in any usage cases.

  3. Ctor/Method Injection is safer than Field/Property Injection.

  4. Ctor/Method Injection makes the DI code clear to which dependencies will be used for the other developers.


Register Mappings to the DI container

DI Container is a hashtable where holds all the dependency registrations.


profile
Unity3D Freelancer Programmer + React

0개의 댓글