An open API service indexing awesome lists of open source software.

https://github.com/ssannandeji/zenject-2019

Dependency Injection Framework for Unity3D
https://github.com/ssannandeji/zenject-2019

data-binding dependency dependency-injection dependency-injection-framework framework game game-development gamedev injection injection-container ioc unity unity3d unity3d-plugin zenject

Last synced: 8 months ago
JSON representation

Dependency Injection Framework for Unity3D

Awesome Lists containing this project

README

          

> ### COMMITMENT TO OPEN SOURCE

>We are proud to provide this useful tool to the community and encourage those developing projects to fork from it. To date Zenject has been forked Over 300 times and we love to see the benefit it is deriving for users and support this!
>
>Modest Tree’s Zenject is open-sourced in order to support the community and encourage collaborative development. This is clearly licensed with an MIT license to allow a high degree of flexibility and freedom of use.
>
We look forward to hearing about the cool projects you are building with Zenject and supporting its use!
Contact us through github or zenject@modesttree.com.

## Upcoming Update

As our Team is looking at Improving and Supporting Zenject, Below is the list of Features and Changes we are planning on applying to Zenject.

* move all pooling functionality into the factories
* add Free() to all IFactory types and have the default Free() dispose
* change pooling to allow a pooled object to be returned to pool via PoolFactory.Free()
* add a PoolHandle struct and IFactory.CreateHandle(), disposing the handle returns object to factory
* eliminate all pooling dependancies from the types being pooled
* add additional install functions to control pooling via installers rather than by explicit code
* PRO: when using PoolHandles, pooling or non-pooling is completely transparent to the consuming types
* CON: breaking changes with existing pooling techniques
>
* move unity-specific handling out of zenject core and into an additional library
* initially zenject was unity-only but now it is now used in standalone .EXE as well
* zenject codebase shows many scars from when it was unity-only
* eliminate all the #IFDEFs and move unity-specifics to external package
* allow building zenject core to DLL, unity-specifics stay as c# in unity project
* PRO: reduces compile times in unity
* PRO: more usable outside unity, fewer unity-landmines to step on
* PRO: far less zenject code to step through when debugging user-code
* CON: may require manual updating of some unity scenes and prefabs
>
* add dependancy graph resolve support

* somebody first needs to understand how zenject stores its bindings. I currently do not.
* we wana dump all the bindings for a set of scenes/installers to xml or something
* an external python or winforms tool allows viewing the binding graph
* show each container as a node, bindings are child nodes, draw dependancy links between bindings,this will make finding unnecessary bindings and fixing binding errors a lot easier,eventually we can also add a binding editor and error highlighting for bad bindings
* PRO: quality-of-life and general workflow improvement
* CON: additional software to maintain

We are sharing this with community to help us prioritize and Find out if there is anything else that the community is looking for in the upcoming release. Looking forward to your feedback - Contact us through github or zenject@modesttree.com.
##
>
Zenject

## Dependency Injection Framework for Unity3D

[![Join the chat at https://gitter.im/Zenject/Lobby](https://badges.gitter.im/Zenject/Lobby.svg)](https://gitter.im/Zenject/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

## Introduction

Zenject is a lightweight highly performant dependency injection framework built specifically to target Unity 3D (however it can be used outside of Unity as well). It can be used to turn your application into a collection of loosely-coupled parts with highly segmented responsibilities. Zenject can then glue the parts together in many different configurations to allow you to easily write, re-use, refactor and test your code in a scalable and extremely flexible way.

Tested in Unity 3D on the following platforms:
* PC/Mac/Linux
* iOS
* Android
* WebGL
* PS4 (with IL2CPP backend)
* Windows Store (including 8.1, Phone 8.1, Universal 8.1 and Universal 10 - both .NET and IL2CPP backend)

IL2CPP is supported, however there are some gotchas - see here for details

This project is open source. You can find the official repository [here](https://github.com/modesttree/Zenject).

For general troubleshooting / support, please post to [stack overflow](https://stackoverflow.com/questions/ask) using the tag 'zenject', or post in the [zenject google group](https://groups.google.com/forum/#!forum/zenject/)

Or, if you have found a bug, you are also welcome to create an issue on the [github page](https://github.com/modesttree/Zenject), or a pull request if you have a fix / extension. There is also a [gitter chat](https://gitter.im/Zenject/Lobby) that you can join for real time discussion. You can also follow [@Zenject](https://twitter.com/Zenject) on twitter for updates.

## Features

* Injection
* Supports both normal C# classes and MonoBehaviours
* Constructor injection
* Field injection
* Property injection
* Method injection
* Conditional binding (eg. by type, by name, etc.)
* Optional dependencies
* Support for creating objects after initialization using factories
* Nested Containers aka Sub-Containers
* Injection across different Unity scenes to pass information from one scene to the next
* Scene parenting, to allow one scene to inherit the bindings from another
* Support for global, project-wide bindings to add dependencies for all scenes
* Convention based binding, based on class name, namespace, or any other criteria
* Ability to validate object graphs at editor time (including dynamic object graphs created via factories)
* Automatic binding on components in the scene using the `ZenjectBinding` component
* Auto-Mocking using the Moq library
* Built-in support for memory pools
* Support for decorator pattern using decorator bindings
* Support for automatically mapping open generic types
* Built in support for unit test, integration tests, and scene tests
* Just-in-time injection using the LazyInject<> construct
* Support for multiple threads for resolving/instantiating
* Support for 'reflection baking' to eliminate costly reflection operations completely by directly modifying the generated assemblies
* Automatic injection of game objects using ZenAutoInjecter component

## Installation

You can install Zenject using any of the following methods

1. From [Releases Page](https://github.com/modesttree/Zenject/releases). Here you can choose between the following:

* **Zenject-WithAsteroidsDemo.vX.X.unitypackage** - This is equivalent to what you find in the Asset Store and contains both sample games "Asteroids" and "SpaceFighter" as part of the package. All the source code for Zenject is included here.
* **Zenject.vX.X.unitypackage** - Same as above except without the Sample projects.
* **Zenject-NonUnity.vX.X.zip** - Use this if you want to use Zenject outside of Unity (eg. just as a normal C# project)

1. From the [Asset Store Page](http://u3d.as/content/modest-tree-media/zenject-dependency-injection/7ER)

* Normally this should be the same as what you find in the [Releases section](https://github.com/modesttree/Zenject/releases), but may also be slightly out of date since Asset Store can take a week or so to review submissions sometimes.

1. From Source

* After syncing the git repo, note that you will have to build the `Zenject-Usage.dll` by building the solution at `AssemblyBuild\Zenject-usage\Zenject-usage.sln`. Or, if you prefer you can get `Zenject-Usage.dll` from Releases section instead
* Then you can copy the `UnityProject/Assets/Plugins/Zenject` directory to your own Unity3D project.

Note that when importing Zenject into your unity project, you can uncheck any folder underneath the OptionalExtras folder for cases where you don't want to include it, or if you just want the core zenject functionality, you can uncheck the entire OptionalExtras directory.

## History

Unity is a fantastic game engine, however the approach that new developers are encouraged to take does not lend itself well to writing large, flexible, or scalable code bases. In particular, the default way that Unity manages dependencies between different game components can often be awkward and error prone.

This project was started because at the time there wasn't any DI frameworks for Unity, and having used DI frameworks outside of Unity (eg. Ninject) and seeing the benefits, I felt it was important to remedy that.

Finally, I will just say that if you don't have experience with DI frameworks, and are writing object oriented code, then trust me, you will thank me later! Once you learn how to write properly loosely coupled code using DI, there is simply no going back.

## Documentation

The Zenject documentation is split up into the following sections. It is split up into two parts (Introduction and Advanced) so that you can get up and running as quickly as possible. I would recommend at least skimming through the Introduction section before beginning, but then feel free to jump around in the advanced section as necessary

Another great starting point is to watch [this youtube series on zenject](https://www.youtube.com/watch?v=IS2YUIb_w_M&list=PLKERDLXpXl_jNJPY2czQcfPXW4BJaGZc_) created by Infallible Code.

You might also benefit from playing with the provided sample projects (which you can find by opening `Zenject/OptionalExtras/SampleGame1` or `Zenject/OptionalExtras/SampleGame2`).

If you are a DI veteran, then it might be worth taking a look at the cheatsheet at the bottom of this page, which should give you an idea of the syntax, which might be all you need to get started.

The tests may also be helpful to show usage for each specific feature (which you can find at `Zenject/OptionalExtras/UnitTests` and `Zenject/OptionalExtras/IntegrationTests`)

Also see further reading section for some external zenject tutorials provided elsewhere.

## Table Of Contents

* Introduction
* What is Dependency Injection?
* Theory
* Misconceptions
* Zenject API
* Hello World Example
* Injection
* Binding
* Binding
* Construction Methods
* Installers
* Using Non-MonoBehaviour Classes
* ITickable
* IInitializable
* IDisposable
* BindInterfacesTo and BindInterfacesAndSelfTo
* Using the Unity Inspector To Configure Settings
* Object Graph Validation
* Scene Bindings
* General Guidelines / Recommendations / Gotchas / Tips and Tricks
* Further Reading
* Advanced
* Binding
* Game Object Bind Methods
* Optional Binding
* Conditional Bindings
* List Bindings
* Global Bindings Using Project Context
* Identifiers
* Non Generic bindings
* Convention Based Binding
* Scriptable Object Installer
* Runtime Parameters For Installers
* Creating Objects Dynamically Using Factories
* Memory Pools
* Update / Initialization Order
* Zenject Order Of Operations
* Injecting data across scenes
* Scene Parenting Using Contract Names
* Just-In-Time Resolving Using LazyInject<>
* Scene Decorators
* ZenAutoInjecter
* Sub-Containers And Facades
* Writing Automated Unit Tests / Integration Tests
* Philosophy Of Zenject
* Using Zenject Outside Unity Or For DLLs
* Zenject Settings
* Signals
* Decorator Bindings
* Open Generic Types
* Notes About Destruction/Dispose Order
* UniRx Integration
* Auto-Mocking using Moq
* Creating Unity EditorWindow's with Zenject
* Optimization Recommendations/Notes
* Reflection Baking
* Upgrade Guide for Zenject 6
* DiContainer Methods
* DiContainer.Instantiate
* DiContainer.Bind
* DiContainer.Resolve
* DiContainer.Inject
* DiContainer.QueueForInject
* DiContainer Unbind / Rebind
* Other DiContainer methods
* Frequently Asked Questions
* Isn't this overkill? I mean, is using statically accessible singletons really that bad?
* Is there a way to integrate with the upcoming Unity ECS?
* Does this work on AOT platforms such as iOS and WebGL?
* How is Performance?
* Does Zenject support multithreading?
* Are there any more sample projects with source to look at?
* What games/tools/libraries are using Zenject
* I keep getting errors complaining about circular reference! How to address this?
* Cheat Sheet
* Further Help
* Release Notes
* License

## Theory

What follows is a general overview of Dependency Injection from my perspective. However, it is kept light, so I highly recommend seeking other resources for more information on the subject, as there are many other people (often with better writing ability) that have written about the theory behind it.

When writing an individual class to achieve some functionality, it will likely need to interact with other classes in the system to achieve its goals. One way to do this is to have the class itself create its dependencies, by calling concrete constructors:

```csharp
public class Foo
{
ISomeService _service;

public Foo()
{
_service = new SomeService();
}

public void DoSomething()
{
_service.PerformTask();
...
}
}
```

This works fine for small projects, but as your project grows it starts to get unwieldy. The class Foo is tightly coupled to class 'SomeService'. If we decide later that we want to use a different concrete implementation then we have to go back into the Foo class to change it.

After thinking about this, often you come to the realization that ultimately, Foo shouldn't bother itself with the details of choosing the specific implementation of the service. All Foo should care about is fulfilling its own specific responsibilities. As long as the service fulfills the abstract interface required by Foo, Foo is happy. Our class then becomes:

```csharp
public class Foo
{
ISomeService _service;

public Foo(ISomeService service)
{
_service = service;
}

public void DoSomething()
{
_service.PerformTask();
...
}
}
```

This is better, but now whatever class is creating Foo (let's call it Bar) has the problem of filling in Foo's extra dependencies:

```csharp
public class Bar
{
public void DoSomething()
{
var foo = new Foo(new SomeService());
foo.DoSomething();
...
}
}
```

And class Bar probably also doesn't really care about what specific implementation of SomeService Foo uses. Therefore we push the dependency up again:

```csharp
public class Bar
{
ISomeService _service;

public Bar(ISomeService service)
{
_service = service;
}

public void DoSomething()
{
var foo = new Foo(_service);
foo.DoSomething();
...
}
}
```

So we find that it is useful to push the responsibility of deciding which specific implementations of which classes to use further and further up in the 'object graph' of the application. Taking this to an extreme, we arrive at the entry point of the application, at which point all dependencies must be satisfied before things start. The dependency injection lingo for this part of the application is called the 'composition root'. It would normally look like this:

```csharp
var service = new SomeService();
var foo = new Foo(service);
var bar = new Bar(service);
var qux = new Qux(bar);

.. etc.
```

DI frameworks such as Zenject simply help automate this process of creating and handing out all these concrete dependencies, so that you don't need to explicitly do so yourself like in the above code.

## Misconceptions

There are many misconceptions about DI, due to the fact that it can be tricky to fully wrap your head around at first. It will take time and experience before it fully 'clicks'.

As shown in the above example, DI can be used to easily swap different implementations of a given interface (in the example this was ISomeService). However, this is only one of many benefits that DI offers.

More important than that is the fact that using a dependency injection framework like Zenject allows you to more easily follow the '[Single Responsibility Principle](http://en.wikipedia.org/wiki/Single_responsibility_principle)'. By letting Zenject worry about wiring up the classes, the classes themselves can just focus on fulfilling their specific responsibilities.

Another common mistake that people new to DI make is that they extract interfaces from every class, and use those interfaces everywhere instead of using the class directly. The goal is to make code more loosely coupled, so it's reasonable to think that being bound to an interface is better than being bound to a concrete class. However, in most cases the various responsibilities of an application have single, specific classes implementing them, so using interfaces in these cases just adds unnecessary maintenance overhead. Also, concrete classes already have an interface defined by their public members. A good rule of thumb instead is to only create interfaces when the class has more than one implementation or in cases where you intend to have multiple implemenations in the future (this is known, by the way, as the [Reused Abstraction Principle](http://codemanship.co.uk/parlezuml/blog/?postid=934))

Other benefits include:

* Refactorability - When code is loosely coupled, as is the case when using DI properly, the entire code base is much more resilient to changes. You can completely change parts of the code base without having those changes wreak havoc on other parts.
* Encourages modular code - When using a DI framework you will naturally follow better design practices, because it forces you to think about the interfaces between classes.
* Testability - Writing automated unit tests or user-driven tests becomes very easy, because it is just a matter of writing a different 'composition root' which wires up the dependencies in a different way. Want to only test one subsystem? Simply create a new composition root. Zenject also has some support for avoiding code duplication in the composition root itself (using Installers - described below).

Also see here and here for further discussion and justification for using a DI framework.

## Hello World Example

```csharp
using Zenject;
using UnityEngine;
using System.Collections;

public class TestInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind().FromInstance("Hello World!");
Container.Bind().AsSingle().NonLazy();
}
}

public class Greeter
{
public Greeter(string message)
{
Debug.Log(message);
}
}
```

You can run this example by doing the following:

* Create a new scene in Unity
* Right Click inside the Hierarchy tab and select `Zenject -> Scene Context`
* Right Click in a folder within the Project Tab and Choose `Create -> Zenject -> MonoInstaller`. Name it TestInstaller.cs
* Add your TestInstaller script to the scene (as its own GameObject or on the same GameObject as the SceneContext, it doesn't matter)
* Add a reference to your TestInstaller to the properties of the SceneContext by adding a new row in the inspector of the "Installers" property (press the + button) and then dragging TestInstaller to it
* Open up TestInstaller and paste the above code into it
* Validate your scene by either selecting Edit -> Zenject -> Validate Current Scene or hitting CTRL+ALT+V. (note that this step isn't necessary but good practice to get into)
* Run
* Note also, that you can use the shortcut `CTRL+SHIFT+R` to "validate then run". Validation is usually fast enough that this does not add a noticeable overhead to running your game, and when it does detect errors it is much faster to iterate on since you avoid the startup time.
* Observe unity console for output

The SceneContext MonoBehaviour is the entry point of the application, where Zenject sets up all the various dependencies before kicking off your scene. To add content to your Zenject scene, you need to write what is referred to in Zenject as an 'Installer', which declares all the dependencies and their relationships with each other. All dependencies that are marked as "NonLazy" are automatically created after the installers are run, which is why the Greeter class that we added above gets created on startup. If this doesn't make sense to you yet, keep reading!

## Injection

There are many different ways of declaring dependencies on the container, which are documented in the next section. There are also several ways of having these dependencies injected into your classes. These are:

1 - **Constructor Injection**

```csharp
public class Foo
{
IBar _bar;

public Foo(IBar bar)
{
_bar = bar;
}
}
```

2 - **Field Injection**

```csharp
public class Foo
{
[Inject]
IBar _bar;
}
```

Field injection occurs immediately after the constructor is called. All fields that are marked with the `[Inject]` attribute are looked up in the container and given a value. Note that these fields can be private or public and injection will still occur.

3 - **Property Injection**

```csharp
public class Foo
{
[Inject]
public IBar Bar
{
get;
private set;
}
}
```

Property injection works the same as field injection except is applied to C# properties. Just like fields, the setter can be private or public in this case.

4 - **Method Injection**

```csharp
public class Foo
{
IBar _bar;
Qux _qux;

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

Method Inject injection works very similarly to constructor injection.

Note the following:

- Inject methods are the recommended approach for MonoBehaviours, since MonoBehaviours cannot have constructors.
- There can be any number of inject methods. In this case, they are called in the order of Base class to Derived class. This can be useful to avoid the need to forward many dependencies from derived classes to the base class via constructor parameters, while also guaranteeing that the base class inject methods complete first, just like how constructors work.
- Inject methods are called after all other injection types. It is designed this way so that these methods can be used to execute initialization logic which might make use of injected fields or properties. Note also that you can leave the parameter list empty if you just want to do some initialization logic only.
- You can safely assume that the dependencies that you receive via inject methods will themselves already have been injected (the only exception to this is in the case where you have circular dependencies). This can be important if you use inject methods to perform some basic initialization, since in that case you may need the given dependencies to be initialized as well
- Note however that it is usually not a good idea to use inject methods for initialization logic. Often it is better to use 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 constructor/method injection compared to field/property injection.
* Constructor injection forces the dependency to only be resolved once, at class creation, which is usually what you want. In most cases you don't want to expose a public property for your initial dependencies because this suggests that it's open to changing.
* Constructor injection guarantees no circular dependencies between classes, which is generally a bad thing to do. Zenject does allow circular dependencies when using other injections types however such as method/field/property injection
* Constructor/Method injection is more portable for cases where you decide to re-use the code without a DI framework such as Zenject. You can do the same with public properties but it's more error prone (it's easier to forget to initialize one field and leave the object in an invalid state)
* Finally, Constructor/Method injection makes it clear what all the dependencies of a class are when another programmer is reading the code. They can simply look at the parameter list of the method. This is also good because it will be more obvious when a class has too many dependencies and should therefore be split up (since its constructor parameter list will start to seem long)

## Binding

Every dependency injection framework is ultimately just a framework to bind types to instances.

In Zenject, dependency mapping is done by adding bindings to something called a container. The container should then 'know' how to create all the object instances in your application, by recursively resolving all dependencies for a given object.

When the container is asked to construct an instance of a given type, it uses C# reflection to find the list of constructor arguments, and all fields/properties that are marked with an `[Inject]` attribute. It then attempts to resolve each of these required dependencies, which it uses to call the constructor and create the new instance.

Each Zenject application therefore must tell the container how to resolve each of these dependencies, which is done via Bind commands. For example, given the following class:

```csharp
public class Foo
{
IBar _bar;

public Foo(IBar bar)
{
_bar = bar;
}
}
```

You can wire up the dependencies for this class with the following:

```csharp
Container.Bind().AsSingle();
Container.Bind().To().AsSingle();
```

This tells Zenject that every class that requires a dependency of type Foo should use the same instance, which it will automatically create when needed. And similarly, any class that requires the IBar interface (like Foo) will be given the same instance of type Bar.

The full format for the bind command is the following. Note that in most cases you will not use all of these methods and that they all have logical defaults when unspecified


Container.Bind<ContractType>()
.WithId(Identifier)
.To<ResultType>()
.FromConstructionMethod()
.AsScope()
.WithArguments(Arguments)
.OnInstantiated(InstantiatedCallback)
.When(Condition)
.(Copy|Move)Into(All|Direct)SubContainers()
.NonLazy()
.IfNotBound();

Where:

* **ContractType** = The type that you are creating a binding for.

* This value will correspond to the type of the field/parameter that is being injected.

* **ResultType** = The type to bind to.

* Default: **ContractType**
* This type must either to equal to **ContractType** or derive from **ContractType**. If unspecified, it assumes ToSelf(), which means that the **ResultType** will be the same as the **ContractType**. This value will be used by whatever is given as the **ConstructionMethod** to retrieve an instance of this type

* **Identifier** = The value to use to uniquely identify the binding. This can be ignored in most cases, but can be quite useful in cases where you need to distinguish between multiple bindings with the same contract type. See here for details.

* **ConstructionMethod** = The method by which an instance of **ResultType** is created/retrieved. See this section for more details on the various construction methods.

* Default: FromNew()
* Examples: eg. FromGetter, FromMethod, FromResolve, FromComponentInNewPrefab, FromSubContainerResolve, FromInstance, etc.

* **Scope** = This value determines how often (or if at all) the generated instance is re-used across multiple injections.

* Default: AsTransient. Note however that not all bindings have a default, so an exception will be thrown if not supplied. The bindings that do not require the scope to be set explicitly are any binding with a construction method that is a search rather than creating a new object from scratch (eg. FromMethod, FromComponentX, FromResolve, etc.)
* It can be one of the following:
1. **AsTransient** - Will not re-use the instance at all. Every time **ContractType** is requested, the DiContainer will execute the given construction method again
2. **AsCached** - Will re-use the same instance of **ResultType** every time **ContractType** is requested, which it will lazily generate upon first use
3. **AsSingle** - Exactly the same as AsCached, except that it will sometimes throw exceptions if there already exists a binding for **ResultType**. It is simply a way to ensure that the given **ResultType** is unique within the container. Note however that it will only guarantee that there is only one instance across the given container, which means that using AsSingle with the same binding in a sub-container could generate a second instance.

* In most cases, you will likely want to just use AsSingle, however AsTransient and AsCached have their uses too.

* **Arguments** = A list of objects to use when constructing the new instance of type **ResultType**. This can be useful as an alternative to adding other bindings for the arguments in the form `Container.BindInstance(arg).WhenInjectedInto()`
* **InstantiatedCallback** = In some cases it is useful to be able customize an object after it is instantiated. In particular, if using a third party library, it might be necessary to change a few fields on one of its types. For these cases you can pass a method to OnInstantiated that can customize the newly created instance. For example:

```csharp
Container.Bind().AsSingle().OnInstantiated(OnFooInstantiated);

void OnFooInstantiated(InjectContext context, Foo foo)
{
foo.Qux = "asdf";
}
```

Or, equivalently:

```csharp
Container.Bind().AsSingle().OnInstantiated((ctx, foo) => foo.Bar = "qux");
```

Note that you can also bind a custom factory using FromFactory that directly calls Container.InstantiateX before customizing it for the same effect, but OnInstantiated can be easier in some cases

* **Condition** = The condition that must be true for this binding to be chosen. See here for more details.
* (**Copy**|**Move**)Into(**All**|**Direct**)SubContainers = This value can be ignored for 99% of users. It can be used to automatically have the binding inherited by subcontainers. For example, if you have a class Foo and you want a unique instance of Foo to be automatically placed in the container and every subcontainer, then you could add the following binding:

```csharp
Container.Bind().AsSingle().CopyIntoAllSubContainers()
```

In other words, the result will be equivalent to copying and pasting the `Container.Bind().AsSingle()` statement into the installer for every sub-container.

Or, if you only wanted Foo in the subcontainers and not the current container:

```csharp
Container.Bind().AsSingle().MoveIntoAllSubContainers()
```

Or, if you only wanted Foo to be in the immediate child subcontainer, and not the subcontainers of these subcontainers:

```csharp
Container.Bind().AsSingle().MoveIntoDirectSubContainers()
```

* **NonLazy** = Normally, the **ResultType** is only ever instantiated when the binding is first used (aka "lazily"). However, when NonLazy is used, **ResultType** will immediately be created on startup.

* **IfNotBound** = When this is added to a binding and there is already a binding with the given contract type + identifier, then this binding will be skipped.

## Construction Methods

1. **FromNew** - Create via the C# new operator. This is the default if no construction method is specified.

```csharp
// These are both the same
Container.Bind();
Container.Bind().FromNew();
```

1. **FromInstance** - Add a given instance to the container. Note that the given instance will not be injected in this case. If you also want your instance to be injected at startup, see QueueForInject

```csharp
Container.Bind().FromInstance(new Foo());

// You can also use this short hand which just takes ContractType from the parameter type
Container.BindInstance(new Foo());

// This is also what you would typically use for primitive types
Container.BindInstance(5.13f);
Container.BindInstance("foo");

// Or, if you have many instances, you can use BindInstances
Container.BindInstances(5.13f, "foo", new Foo());
```

1. **FromMethod** - Create via a custom method

```csharp
Container.Bind().FromMethod(SomeMethod);

Foo SomeMethod(InjectContext context)
{
...
return new Foo();
}
```

1. **FromMethodMultiple** - Same as FromMethod except allows returning multiple instances at once (or zero).

```csharp
Container.Bind().FromMethodMultiple(GetFoos);

IEnumerable GetFoos(InjectContext context)
{
...
return new Foo[]
{
new Foo(),
new Foo(),
new Foo(),
}
}
```

1. **FromFactory** - Create instance using a custom factory class. This construction method is similar to `FromMethod` except can be cleaner in cases where the logic is more complicated or requires dependencies (since the factory itself can have dependencies injected)

```csharp
class FooFactory : IFactory
{
public Foo Create()
{
// ...
return new Foo();
}
}

Container.Bind().FromFactory()
```

1. **FromIFactory** - Create instance using a custom factory class. This is a more generic and more powerful alternative to FromFactory, because you can use any kind of construction method you want for your custom factory (unlike FromFactory which assumes `FromNew().AsCached()`)

For example, you could use a factory that is a scriptable object like this:

```csharp
class FooFactory : ScriptableObject, IFactory
{
public Foo Create()
{
// ...
return new Foo();
}
}

Container.Bind().FromIFactory(x => x.To().FromScriptableObjectResource("FooFactory")).AsSingle();
```

Or, you might want to have your custom factory be placed in a subcontainer like this:

```csharp
public class FooFactory : IFactory
{
public Foo Create()
{
return new Foo();
}
}

public override void InstallBindings()
{
Container.Bind().FromIFactory(x => x.To().FromSubContainerResolve().ByMethod(InstallFooFactory)).AsSingle();
}

void InstallFooFactory(DiContainer subContainer)
{
subContainer.Bind().AsSingle();
}
```

Also note that the following two lines are equivalent:

```csharp
Container.Bind().FromFactory().AsSingle();
Container.Bind().FromIFactory(x => x.To().AsCached()).AsSingle();
```

1. **FromComponentInNewPrefab** - Instantiate the given prefab as a new game object, inject any MonoBehaviour's on it, and then search the result for type **ResultType** in a similar way that `GetComponentInChildren` works

```csharp
Container.Bind().FromComponentInNewPrefab(somePrefab);
```

**ResultType** must either be an interface or derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

Note that if there are multiple matches for **ResultType** on the prefab it will only match the first one encountered just like how GetComponentInChildren works. So if you are binding a prefab and there isn't a specific MonoBehaviour/Component that you want to bind to, you can just choose Transform and it will match the root of the prefab.

1. **FromComponentsInNewPrefab** - Same as FromComponentInNewPrefab except will match multiple values or zero values. You might use it for example and then inject `List` somewhere. Can be thought of as similar to `GetComponentsInChildren`

1. **FromComponentInNewPrefabResource** - Instantiate the given prefab (found at the given resource path) as a new game object, inject any MonoBehaviour's on it, and then search the result for type **ResultType** in a similar way that `GetComponentInChildren` works (in that it will return the first matching value found)

```csharp
Container.Bind().FromComponentInNewPrefabResource("Some/Path/Foo");
```

**ResultType** must either be an interface or derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

1. **FromComponentsInNewPrefabResource** - Same as FromComponentInNewPrefab except will match multiple values or zero values. You might use it for example and then inject `List` somewhere. Can be thought of as similar to `GetComponentsInChildren`

1. **FromNewComponentOnNewGameObject** - Create a new empty game object and then instantiate a new component of the given type on it.

```csharp
Container.Bind().FromNewComponentOnNewGameObject();
```

**ResultType** must derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

1. **FromNewComponentOnNewPrefab** - Instantiate the given prefab as a new game object and also instantiate a new instance of the given component on the root of the new game object. NOTE: It is not necessary that the prefab contains a copy of the given component.

```csharp
Container.Bind().FromNewComponentOnNewPrefab(somePrefab);
```

**ResultType** must derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

1. **FromNewComponentOnNewPrefabResource** - Instantiate the given prefab (found at the given resource path) and also instantiate a new instance of the given component on the root of the new game object. NOTE: It is not necessary that the prefab contains a copy of the given component.

```csharp
Container.Bind().FromNewComponentOnNewPrefabResource("Some/Path/Foo");
```

**ResultType** must derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

1. **FromNewComponentOn** - Instantiate a new component of the given type on the given game object

```csharp
Container.Bind().FromNewComponentOn(someGameObject);
```

**ResultType** must derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

1. **FromNewComponentSibling** - Instantiate a new component of the given on the current transform. The current transform here is taken from the object being injected, which must therefore be a MonoBehaviour derived type.

```csharp
Container.Bind().FromNewComponentSibling();
```

Note that if the given component type is already attached to the current transform that this will just return that instead of creating a new component. As a result, this bind statement functions similar to Unity's [RequireComponent] attribute.

**ResultType** must derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

Also note that if a non-MonoBehaviour requests the given type, an exception will be thrown, since there is no current transform in that case.

1. **FromComponentInHierarchy** - Look up the component within the scene hierarchy associated with the current context, as well as the hierarchy associated with any parent contexts. Works similar to `GetComponentInChildren` in that it will return the first matching value found

```csharp
Container.Bind().FromComponentInHierarchy().AsSingle();
```

**ResultType** must either be an interface or derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

In the most common case where the context is a SceneContext, this will search the entire scene hierarchy (except any sub-contexts such as GameObjectContext). In other words, when the current context is a scene context, it will behave similar to `GameObject.FindObjectsOfType`. Note that since this could be a big search, it should be used with caution, just like `GameObject.FindObjectsOfType` should be used with caution.

In the case where the context is GameObjectContext, it will only search within and underneath the game object root (and any parent contexts).

In the case where the context is ProjectContext, it will only search within the project context prefab

1. **FromComponentsInHierarchy** - Same as FromComponentInHierarchy except will match multiple values or zero values. You might use it for example and then inject `List` somewhere. Can be thought of as similar to `GetComponentsInChildren`

1. **FromComponentSibling** - Look up the given component type by searching over the components that are attached to the current transform. The current transform here is taken from the object being injected, which must therefore be a MonoBehaviour derived type.

```csharp
Container.Bind().FromComponentSibling();
```

**ResultType** must either be an interface or derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

Note that if a non-MonoBehaviour requests the given type, an exception will be thrown, since there is no current transform in that case.

1. **FromComponentsSibling** - Same as FromComponentSibling except will match multiple values or zero values.

1. **FromComponentInParents** - Look up the component by searching the current transform or any parent for the given component type. The current transform here is taken from the object being injected, which must therefore be a MonoBehaviour derived type.

```csharp
Container.Bind().FromComponentInParents();
```

**ResultType** must either be an interface or derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

Note that if a non-MonoBehaviour requests the given type, an exception will be thrown, since there is no current transform in that case.

1. **FromComponentsInParents** - Same as FromComponentInParents except will match multiple values or zero values. You might use it for example and then inject `List` somewhere

1. **FromComponentInChildren** - Look up the component by searching the current transform or any child transform for the given component type. The current transform here is taken from the object being injected, which must therefore be a MonoBehaviour derived type. Similar to `GetComponentInChildren` in that it will return the first matching value found

```csharp
Container.Bind().FromComponentInChildren();
```

**ResultType** must either be an interface or derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

Note that if a non-MonoBehaviour requests the given type, an exception will be thrown, since there is no current transform in that case.

1. **FromComponentsInChildren** - Same as FromComponentInChildren except will match multiple values or zero values. You might use it for example and then inject `List` somewhere. Can be thought of as similar to `GetComponentsInChildren`

1. **FromNewComponentOnRoot** - Instantiate the given component on the root of the current context. This is most often used with GameObjectContext.

```csharp
Container.Bind().FromNewComponentOnRoot();
```

**ResultType** must derive from UnityEngine.MonoBehaviour / UnityEngine.Component in this case

1. **FromResource** - Create by calling the Unity3d function `Resources.Load` for **ResultType**. This can be used to load any type that `Resources.Load` can load, such as textures, sounds, prefabs, etc.

```csharp
Container.Bind().WithId("Glass").FromResource("Some/Path/Glass");
```

1. **FromResources** - Same as FromResource except will match multiple values or zero values. You might use it for example and then inject `List` somewhere

1. **FromScriptableObjectResource** - Bind directly to the scriptable object instance at the given resource path. NOTE: Changes to this value while inside unity editor will be saved persistently. If this is undesirable, use FromNewScriptableObjectResource.

```csharp
public class Foo : ScriptableObject
{
}

Container.Bind().FromScriptableObjectResource("Some/Path/Foo");
```

1. **FromNewScriptableObjectResource** - Same as FromScriptableObjectResource except it will instantiate a new copy of the given scriptable object resource. This can be useful if you want to have multiple distinct instances of the given scriptable object resource, or if you want to ensure that the saved values for the scriptable object are not affected by changing at runtime.

1. **FromResolve** - Get instance by doing another lookup on the container (in other words, calling `DiContainer.Resolve()`). Note that for this to work, **ResultType** must be bound in a separate bind statement. This construction method can be especially useful when you want to bind an interface to another interface, as shown in the below example

```csharp
public interface IFoo
{
}

public interface IBar : IFoo
{
}

public class Foo : IBar
{
}

Container.Bind().To().FromResolve();
Container.Bind().To();
```

1. **FromResolveAll** - Same as FromResolve except will match multiple values or zero values.

1. **FromResolveGetter<ObjectType>** - Get instance from the property of another dependency which is obtained by doing another lookup on the container (in other words, calling `DiContainer.Resolve()` and then accessing a value on the returned instance of type **ResultType**). Note that for this to work, **ObjectType** must be bound in a separate bind statement.

```csharp
public class Bar
{
}

public class Foo
{
public Bar GetBar()
{
return new Bar();
}
}

Container.Bind();
Container.Bind().FromResolveGetter(x => x.GetBar());
```

1. **FromResolveAllGetter<ObjectType>** - Same as FromResolveGetter except will match multiple values or zero values.

1. **FromSubContainerResolve** - Get **ResultType** by doing a lookup on a subcontainer. Note that for this to work, the sub-container must have a binding for **ResultType**. This approach can be very powerful, because it allows you to group related dependencies together inside a mini-container, and then expose only certain classes (aka "Facades") to operate on this group of dependencies at a higher level. For more details on using sub-containers, see this section. There are several ways to define the subcontainer:

1. **ByNewPrefabMethod** - Initialize subcontainer by instantiating a new prefab. Note that unlike `ByNewContextPrefab`, this bind method does not require that there be a GameObjectContext attached to the prefab. In this case the GameObjectContext is added dynamically and then run with the given installer method.

```csharp
Container.Bind().FromSubContainerResolve().ByNewPrefabMethod(MyPrefab, InstallFoo);

void InstallFoo(DiContainer subContainer)
{
subContainer.Bind();
}
```

1. **ByNewPrefabInstaller** - Initialize subcontainer by instantiating a new prefab. Same as ByNewPrefabMethod, except it initializes the dynamically created GameObjectContext with the given installer rather than a method.

```csharp
Container.Bind().FromSubContainerResolve().ByNewPrefabInstaller(MyPrefab);

class FooInstaller : Installer
{
public override void InstallBindings()
{
Container.Bind();
}
}
```

1. **ByNewPrefabResourceMethod** - Initialize subcontainer instantiating a new prefab obtained via `Resources.Load`. Note that unlike `ByNewPrefabResource`, this bind method does not require that there be a GameObjectContext attached to the prefab. In this case the GameObjectContext is added dynamically and then run with the given installer method.

```csharp
Container.Bind().FromSubContainerResolve().ByNewPrefabResourceMethod("Path/To/MyPrefab", InstallFoo);

void InstallFoo(DiContainer subContainer)
{
subContainer.Bind();
}
```

1. **ByNewPrefabResourceInstaller** - Initialize subcontainer instantiating a new prefab obtained via `Resources.Load`. Same as ByNewPrefabResourceMethod, except it initializes the dynamically created GameObjectContext with the given installer rather than a method.

```csharp
Container.Bind().FromSubContainerResolve().ByNewPrefabResourceInstaller("Path/To/MyPrefab");

class FooInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind();
}
}
```

1. **ByNewGameObjectInstaller** - Initialize subcontainer by instantiating a empty game object, attaching GameObjectContext, and then installing using the given installer. This approach is very similar to ByInstaller except has the following advantages:

- Any ITickable, IInitializable, IDisposable, etc. bindings will be called properly
- Any new game objects that are instantiated inside the subcontainer will be parented underneath the game object context object
- You can destroy the subcontainer by just destroying the game object context game object

1. **ByNewGameObjectMethod** - Same as ByNewGameObjectInstaller except the subcontainer is initialized based on the given method rather than an installer type.

1. **ByMethod** - Initialize the subcontainer by using a method.

```csharp
Container.Bind().FromSubContainerResolve().ByMethod(InstallFooFacade);

void InstallFooFacade(DiContainer subContainer)
{
subContainer.Bind();
}
```

Note that when using ByMethod, if you want to use zenject interfaces such as ITickable, IInitializable, IDisposable inside your subcontainer then you have to also use the WithKernel bind method like this:

```csharp
Container.Bind().FromSubContainerResolve().ByMethod(InstallFooFacade).WithKernel();

void InstallFooFacade(DiContainer subContainer)
{
subContainer.Bind();
subContainer.Bind().To();
}
```

1. **ByInstaller** - Initialize the subcontainer by using a class derived from `Installer`. This can be a cleaner and less error-prone alternative than `ByMethod`, especially if you need to inject data into the installer itself. Less error prone because when using ByMethod it is common to accidentally use Container instead of subContainer in your method.

```csharp
Container.Bind().FromSubContainerResolve().ByInstaller();

class FooFacadeInstaller : Installer
{
public override void InstallBindings()
{
Container.Bind();
}
}
```

Note that when using ByInstaller, if you want to use zenject interfaces such as ITickable, IInitializable, IDisposable inside your subcontainer then you have to also use the WithKernel bind method like this:

```csharp
Container.Bind().FromSubContainerResolve().ByInstaller().WithKernel();
```

1. **ByNewContextPrefab** - Initialize subcontainer by instantiating a new prefab. Note that the prefab must contain a `GameObjectContext` component attached to the root game object. For details on `GameObjectContext` see this section.

```csharp
Container.Bind().FromSubContainerResolve().ByNewContextPrefab(MyPrefab);

// Assuming here that this installer is added to the GameObjectContext at the root
// of the prefab. You could also use a ZenjectBinding in the case where Foo is a MonoBehaviour
class FooFacadeInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind();
}
}
```

1. **ByNewContextPrefabResource** - Initialize subcontainer instantiating a new prefab obtained via `Resources.Load`. Note that the prefab must contain a `GameObjectContext` component attached to the root game object.

```csharp
Container.Bind().FromSubContainerResolve().ByNewContextPrefabResource("Path/To/MyPrefab");
```

1. **ByInstance** - Initialize the subcontainer by directly using a given instance of DiContainer that you provide yourself. This is only useful in some rare edge cases.

1. **FromSubContainerResolveAll** - Same as FromSubContainerResolve except will match multiple values or zero values.

## Installers

Often, there is some collections of related bindings for each sub-system and so it makes sense to group those bindings into a re-usable object. In Zenject this re-usable object is called an 'installer'. You can define a new installer as follows:

```csharp
public class FooInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind().AsSingle();
Container.BindInterfacesTo().AsSingle();
// etc...
}
}
```

You add bindings by overriding the InstallBindings method, which is called by whatever `Context` the installer has been added to (usually this is `SceneContext`). MonoInstaller is a MonoBehaviour so you can add FooInstaller by attaching it to a GameObject. Since it is a GameObject you can also add public members to it to configure your installer from the Unity inspector. This allows you to add references within the scene, references to assets, or simply tuning data (see here for more information on tuning data).

Note that in order for your installer to be triggered it must be attached to the Installers property of the `SceneContext` object. Installers are installed in the order given to `SceneContext` (with scriptable object installers first, then mono installers, then prefab installers) however this order should not usually matter (since nothing should be instantiated during the install process).

In many cases you want to have your installer derive from MonoInstaller, so that you can have inspector settings. There is also another base class called simply `Installer` which you can use in cases where you do not need it to be a MonoBehaviour.

You can also call an installer from another installer. For example:

```csharp
public class BarInstaller : Installer
{
public override void InstallBindings()
{
...
}
}

public class FooInstaller : MonoInstaller
{
public override void InstallBindings()
{
BarInstaller.Install(Container);
}
}
```

Note that in this case BarInstaller is of type `Installer<>` (note the generic arguments) and not MonoInstaller, which is why we can simply call `BarInstaller.Install(Container)` and don't require that BarInstaller be added to our scene already. Any calls to BarInstaller.Install will immediately instantiate a temporary instance of BarInstaller and then call InstallBindings on it. This will repeat for any installers that this installer installs. Note also that when using the `Installer<>` base class, we always must pass in ourself as the generic argument to `Installer<>`. This is necessary so that the `Installer<>` base class can define the static method `BarInstaller.Install`. It is also designed this way to support runtime parameters (described below).

One of the main reasons we use installers as opposed to just having all our bindings declared all at once for each scene, is to make them re-usable. This is not a problem for installers of type `Installer<>` because you can simply call `FooInstaller.Install` as described above for every scene you wish to use it in, but then how would we re-use a MonoInstaller in multiple scenes?

There are three ways to do this.

1. **Prefab instances within the scene**. After attaching your MonoInstaller to a gameobject in your scene, you can then create a prefab out of it. This is nice because it allows you to share any configuration that you've done in the inspector on the MonoInstaller across scenes (and also have per-scene overrides if you want). After adding it in your scene you can then drag and drop it on to the Installers property of a `Context`

1. **Prefabs**. You can also directly drag your installer prefab from the Project tab into the InstallerPrefabs property of SceneContext. Note that in this case you cannot have per-scene overrides like you can when having the prefab instantiated in your scene, but can be nice to avoid clutter in the scene.

1. **Prefabs within Resources folder**. You can also place your installer prefabs underneath a Resoures folder and install them directly from code by using the Resources path. For details on usage see here.

Another option in addition to `MonoInstaller` and `Installer<>` is to use `ScriptableObjectInstaller` which has some unique advantages (especially for settings) - for details see here.

When calling installers from other installers it is common to want to pass parameters into it. See here for details on how that is done.

## ITickable

In some cases it is preferable to avoid the extra weight of MonoBehaviours in favour of just normal C# classes. Zenject allows you to do this much more easily by providing interfaces that mirror functionality that you would normally need to use a MonoBehaviour for.

For example, if you have code that needs to run per frame, then you can implement the `ITickable` interface:

```csharp
public class Ship : ITickable
{
public void Tick()
{
// Perform per frame tasks
}
}
```

Then, to hook it up in an installer:

```csharp
Container.Bind().To().AsSingle();
```

Or if you don't want to have to always remember which interfaces your class implements, you can use the shortcut described here

Note that the order that the Tick() is called in for all ITickables is also configurable, as outlined here.

Also note that there are interfaces `ILateTickable` and `IFixedTickable` which mirror Unity's LateUpdate and FixedUpdated methods

## IInitializable

If you have some initialization that needs to occur on a given object, you could include this code in the constructor. However, this means that the initialization logic would occur in the middle of the object graph being constructed, so it may not be ideal.

A better alternative is to implement `IInitializable`, and then perform initialization logic in an `Initialize()` method.

Then, to hook it up in an installer:

```csharp
Container.Bind().To().AsSingle();
```

Or if you don't want to have to always remember which interfaces your class implements, you can use the shortcut described here

The `Foo.Initialize` method would then be called after the entire object graph is constructed and all constructors have been called.

Note that the constructors for the initial object graph are called during Unity's Awake event, and that the `IInitializable.Initialize` methods are called immediately on Unity's Start event. Using `IInitializable` as opposed to a constructor is therefore more in line with Unity's own recommendations, which suggest that the Awake phase be used to set up object references, and the Start phase be used for more involved initialization logic.

This can also be better than using constructors or `[Inject]` methods because the initialization order is customizable in a similar way to `ITickable`, as explained here.

```csharp
public class Ship : IInitializable
{
public void Initialize()
{
// Initialize your object here
}
}
```

`IInitializable` works well for start-up initialization, but what about for objects that are created dynamically via factories? (see this section for what I'm referring to here). For these cases you will most likely want to eitehr use an `[Inject]` method or an explicit Initialize method that is called after the object is created. For example:

```csharp
public class Foo
{
[Inject]
IBar _bar;

[Inject]
public void Initialize()
{
...
_bar.DoStuff();
...
}
}
```

## IDisposable

If you have external resources that you want to clean up when the app closes, the scene changes, or for whatever reason the context object is destroyed, you can declare your class as `IDisposable` like below:

```csharp
public class Logger : IInitializable, IDisposable
{
FileStream _outStream;

public void Initialize()
{
_outStream = File.Open("log.txt", FileMode.Open);
}

public void Log(string msg)
{
_outStream.WriteLine(msg);
}

public void Dispose()
{
_outStream.Close();
}
}
```

Then in your installer you can include:

```csharp
Container.Bind(typeof(Logger), typeof(IInitializable), typeof(IDisposable)).To().AsSingle();
```

Or you can use the BindInterfaces shortcut:

```csharp
Container.BindInterfacesAndSelfTo().AsSingle();
```

This works because when the scene changes or your unity application is closed, the unity event `OnDestroy()` is called on all MonoBehaviours, including the SceneContext class, which then triggers `Dispose()` on all objects that are bound to `IDisposable`.

You can also implement the `ILateDisposable` interface which works similar to `ILateTickable` in that it will be called after all `IDisposable` objects have been triggered. However, for most cases you're probably better off setting an explicit execution order instead if the order is an issue.

## BindInterfacesTo and BindInterfacesAndSelfTo

If you end up using the `ITickable`, `IInitializable`, and `IDisposable` interfaces as described above, you will often end up with code like this:

```csharp
Container.Bind(typeof(Foo), typeof(IInitializable), typeof(IDisposable)).To().AsSingle();
```

This can be a bit verbose sometimes. Also, it is not ideal because if I later on decide that Foo doesn't need a `Tick()` or a `Dispose()` then I have to keep the installer in sync.

A better idea might be to just always use the interfaces like this:

```csharp
Container.Bind(new[] { typeof(Foo) }.Concat(typeof(Foo).GetInterfaces())).To().AsSingle();
```

This pattern is useful enough that Zenject includes a custom bind method for it. The above code is equivalent to:

```csharp
Container.BindInterfacesAndSelfTo().AsSingle();
```

Now, we can add and remove interfaces to/from Foo and the installer remains the same.

In some cases you might *only* want to bind the interfaces, and keep Foo hidden from other classes. In that case you would use the BindInterfacesTo method instead:

```csharp
Container.BindInterfacesTo().AsSingle()
```

Which, in this case, would expand to:

```csharp
Container.Bind(typeof(IInitializable), typeof(IDisposable)).To().AsSingle();
```

## Using the Unity Inspector To Configure Settings

One implication of writing most of your code as normal C# classes instead of MonoBehaviour's is that you lose the ability to configure data on them using the inspector. You can however still take advantage of this in Zenject by using the following pattern:

```csharp
public class Foo : ITickable
{
readonly Settings _settings;

public Foo(Settings settings)
{
_settings = settings;
}

public void Tick()
{
Debug.Log("Speed: " + _settings.Speed);
}

[Serializable]
public class Settings
{
public float Speed;
}
}
```

Then, in an installer:

```csharp
public class TestInstaller : MonoInstaller
{
public Foo.Settings FooSettings;

public override void InstallBindings()
{
Container.BindInstance(FooSettings);
Container.BindInterfacesTo().AsSingle();
}
}
```

Or, equivalently:

```csharp
public class TestInstaller : MonoInstaller
{
public Foo.Settings FooSettings;

public override void InstallBindings()
{
Container.BindInterfacesTo().AsSingle().WithArguments(FooSettings);
}
}
```

Now, if we run our scene we can change the speed value to tune the Foo class in real time.

Another (arguably better) way to do this is to use `ScriptableObjectInstaller` instead of `MonoInstaller,` which have the added advantage that you can change your settings at runtime and have those changes automatically persist when play mode is stopped. See here for details.

## Object Graph Validation

**Overview**

The usual workflow when setting up bindings using a DI framework is something like this:

* Add some number of bindings in code
* Execute your app
* Observe a bunch of DI related exceptions
* Modify your bindings to address problem
* Repeat

This works ok for small projects, but as the complexity of your project grows it is often a tedious process. The problem gets worse if the startup time of your application is particularly bad, or when the exceptions only occur from factories at various points at runtime. What would be great is some tool to analyze your object graph and tell you exactly where all the missing bindings are, without requiring the cost of firing up your whole app.

You can do this in Zenject out-of-the-box by executing the menu item `Edit -> Zenject -> Validate Current Scene` or simply hitting `CTRL+ALT+V` with the scenes open that you want to validate. This will execute all installers for the current scene, with the result being a fully bound container. It will then iterate through the object graphs and verify that all bindings can be found (without actually instantiating any of them). In other words, it executes a 'dry run' of the normal startup procedure. Under the hood, this works by storing dummy objects in the container in place of actually instantiating your classes.

Alternatively, you can execute the menu item `Edit -> Zenject -> Validate Then Run` or simply hitting `CTRL+SHIFT+R`. This will validate the scenes you have open and then if validation succeeds, it will start play mode. Validation is usually pretty fast so this can be a good alternative to always just hitting play, especially if your game has a costly startup time.

Note that this will also include factories and memory pools, which is especially helpful because those errors might not be caught until sometime after startup.

There are a few things to be aware of:

- No actual logic code is executed - only install bindings is called. This means that if you have logic inside installers other than bind commands that these will be executed as well and may cause issues when running validation (if that logic requires that the container return actual values)
- **null** values are injected into the dependencies that are actually instantiated such as installers (regardles of what was binded)

You might want to inject some classes even in validation mode. In that case you can mark them with `[ZenjectAllowDuringValidation]`.

Also note that some validation behaviour is configurable in zenjectsettings

**Custom validatables**

If you want to add your own validation logic, you can do this simply by having one of your classes inherit from `IValidatable`. After doing this, as long as your class is bound in an installer somewhere, it will be instantiated during validation and then its `Validate()` method will be called. Note however that any dependencies it has will be injected as null (unless marked with `[ZenjectAllowDuringValidation]` attribute).

Inside the Validate method you can throw exceptions if you want validation to fail, or you can just log information to the console. One common thing that occurs in custom validatables is to instantiate types that would not otherwise be validated. By instantiating them during validation it will ensure that all their dependencies can be resolved.

For example, if you create a custom factory that directly instantiates a type using `Container.Instantiate()`, then `Foo` will not be validated, so you will not find out if it is missing some dependencies until runtime. However you can fix this by having your factory implement `IValidatable` and then calling `Container.Instantiate()` inside the `Validate()` method.

## Scene Bindings

In many cases, you have a number of MonoBehaviours that have been added to the scene within the Unity editor (ie. at editor time not runtime) and you want to also have these MonoBehaviours added to the Zenject Container so that they can be injected into other classes.

The usual way this is done is to add public references to these objects within your installer like this:

```csharp
public class Foo : MonoBehaviour
{
}

public class GameInstaller : MonoInstaller
{
public Foo foo;

public override void InstallBindings()
{
Container.BindInstance(foo);
Container.Bind().To().AsSingle();
}
}

public class GameRunner : IInitializable
{
readonly Foo _foo;

public GameRunner(Foo foo)
{
_foo = foo;
}

public void Initialize()
{
...
}
}
```

This works fine however in some cases this can get cumbersome. For example, if you want to allow an artist to add any number of `Enemy` objects to the scene, and you also want all those `Enemy` objects added to the Zenject Container. In this case, you would have to manually drag each one to the inspector of one of your installers. This is very error prone since its easy to forget one, or to delete the `Enemy` game object but forget to delete the null reference in the inspector for your installer, etc.

Another way to do this would be to use the FromComponentInHierarchy bind method like this:

```csharp
public class GameInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind().FromComponentInHierarchy().AsTransient();
Container.Bind().To().AsSingle();
}
}
```

Now, whenever a dependency of type Foo is required, zenject will search the entire scene for any MonoBehaviours of type Foo. This will function very similarly to use Unity's FindObjectsOfType method every time you want to look up a certain dependency. Note that because this method can be a very heavy operation, you probably want to mark it AsCached or AsSingle like this instead:

```csharp
public class GameInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind().FromComponentInHierarchy().AsCached();
Container.Bind().To().AsSingle();
}
}
```

This way, you only incur the performance hit for the search once the first time it is needed instead of every time it is injected to any class. Note also that we can `FromComponentsInHierarchy` (note the plural) in cases where we expect there to be multiple Foos.

Yet another way to do this is to use the `ZenjectBinding` component. You can do this by adding a `ZenjectBinding` MonoBehaviour to the same game object that you want to be automatically added to the Zenject container.

For example, if you have a MonoBehaviour of type `Foo` in your scene, you can just add `ZenjectBinding` alongside it, and then drag the Foo component into the Component property of the ZenjectBinding component.

ZenjectBinding

Then our installer becomes:

```csharp
public class GameInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind().To().AsSingle();
}
}
```

The `ZenjectBinding` component has the following properties:

* **Bind Type** - This will determine what 'contract type' to use. It can be set to any of the following values:

1. **Self**

This is equivalent to the first example where we did this:

```csharp
Container.Bind().FromInstance(_foo);
```

Or, equivalently:

```csharp
Container.BindInstance(_foo);
```

So if we duplicate this game object to have multiple game objects with `Foo` on them (as well as the `ZenjectBinding`), they will all be bound to the Container this way. So after doing this, we would have to change `GameRunner` above to take a `List` otherwise we would get Zenject exceptions (see here for info on list bindings).

2. **AllInterfaces**

This bind type is equivalent to the following:

```csharp
Container.BindInterfacesTo(_foo.GetType()).FromInstance(_foo);
```

Note however, in this case, that `GameRunner` must ask for type `IFoo` in its constructor. If we left `GameRunner` asking for type `Foo` then Zenject would throw exceptions, since the `BindInterfaces` method only binds the interfaces, not the concrete type. If you want the concrete type as well then you can use:

3. **AllInterfacesAndSelf**

This bind type is equivalent to the following:

```csharp
Container.BindInterfacesAndSelfTo(_foo.GetType()).FromInstance(_foo);
```

This is the same as `AllInterfaces` except we can directly access Foo using type `Foo` instead of needing an interface.

4. **BaseType**

This bind type is equivalent to the following:

```csharp
Container.Bind(_foo.GetType().BaseType()).FromInstance(_foo)
```

* **Identifier** - This value can be left empty most of the time. It will determine what is used as the identifier for the binding. For example, when set to "Foo1", it is equivalent to doing the following:

```csharp
Container.BindInstance(_foo).WithId("Foo1");
```

* **Use Scene Context** - This is optional but useful in cases where you want to bind a dependency that is inside a GameObjectContext to the SceneContext. You could also drag the SceneContext to the Context properly but this flag is a bit easier.

* **Context** - This is completely optional and in most cases should be left unset. This will determine which `Context` to apply the binding to. If left unset, it will use whatever context the GameObject is in. In most cases this will be `SceneContext,` but if it's inside a `GameObjectContext` it will be bound into the `GameObjectContext` container instead. One important use case for this field is to allow dragging the `SceneContext` into this field, for cases where the component is inside a `GameObjectContext.` This allows you to treat this MonoBehaviour as a Facade for the entire sub-container given by the `GameObjectContext.`

## General Guidelines / Recommendations / Gotchas / Tips and Tricks

* **Do not use GameObject.Instantiate if you want your objects to have their dependencies injected**
* If you want to instantiate a prefab at runtime and have any MonoBehaviour's automatically injected, we recommend using a factory. You can also instantiate a prefab by directly using the DiContainer by calling any of the InstantiatePrefab methods. Using these ways as opposed to GameObject.Instantiate will ensure any fields that are marked with the `[Inject]` attribute are filled in properly, and all `[Inject]` methods within the prefab are called.

* **Best practice with DI is to *only* reference the container in the composition root "layer"**
* Note that factories are part of this layer and the container can be referenced there (which is necessary to create objects at runtime). See here for more details on this.

* **Do not use IInitializable, ITickable and IDisposable for dynamically created objects**
* Objects that are of type `IInitializable` are only initialized once - at startup during Unity's `Start` phase. If you create an object through a factory, and it derives from `IInitializable`, the `Initialize()` method will not be called. You should use `[Inject]` methods in this case or call Initialize() explicitly yourself after calling Create.
* The same applies to `ITickable` and `IDisposable`. Deriving from these will do nothing unless they are part of the original object graph created at startup.
* If you have dynamically created objects that have an `Update()` method, it is usually best to call `Update()` on those manually, and often there is a higher level manager-like class in which it makes sense to do this from. If however you prefer to use `ITickable` for dynamically objects you can declare a dependency to `TickableManager` and add/remove it explicitly as well.

* **Using multiple constructors**
* You can have multiple constructors however you must mark one of them with the `[Inject]` attribute so Zenject knows which one to use. If you have multiple constructors and none of them are marked with `[Inject]` then Zenject will guess that the intended constructor is the one with the least amount of arguments.

* **Lazily instantiated objects and the object graph**
* Zenject does not immediately instantiate every object defined by the bindings that you've set up in your installers. It will only instantiate those bindings that are marked `NonLazy`. All other bindings are only instantiated when they are needed. All the `NonLazy` objects as well as all their dependencies form the 'initial object graph' of the application. Note that this automatically includes all types that implement `IInitializable,` `ITickable,` `IDisposable,` etc. So if you have a binding that is not being created because nothing in the initial object graph references it, then you can make this explicit by adding `NonLazy` to your binding

* **Restrict the use of bind commands to the 'composition root' only**. In other words, do not make calls to `Container.Bind`, `Container.Rebind`, or `Container.Unbind` after the install phase is completed. This important because immediately after install completes the initial object graph of your application is constructed, and needs access to the full set of bindings.

* **The order that things occur in is wrong, like injection is occurring too late, or Initialize() event is not called at the right time, etc.**
* It may be because the 'script execution order' of the Zenject classes `ProjectKernel` or `SceneKernel` or `SceneContext` is incorrect. These classes should always have the earliest or near earliest execution order. This should already be set by default (since this setting is included in the `cs.meta` files for these classes). However if you are compiling Zenject yourself or have a unique configuration, you may want to make sure, which you can do by going to "Edit -> Project Settings -> Script Execution Order" and confirming that these classes are at the top, before the default time.

## Further Reading

Tutorials Provided Elsewhere:
* [Getting Started With Zenject](https://www.youtube.com/watch?v=IS2YUIb_w_M&list=PLKERDLXpXl_jNJPY2czQcfPXW4BJaGZc_)
* [Udemy course](https://www.udemy.com/dependency-injection-in-unity3d-using-zenject/)
* [Chris' Tutorials on Zenject](https://www.youtube.com/watch?v=Bcj35ceGCn0&list=PLyH-qXFkNSxnJbZLrxF0jWGyHB-8Kcd5q)
* [A better architecture for Unity projects](http://www.gamasutra.com/blogs/RubenTorresBonet/20180703/316442/A_better_architecture_for_Unity_projects.php)
* [Development For Winners](https://grofit.gitbooks.io/development-for-winners/content/)

## Game Object Bind Methods

For bindings that create new game objects (eg. `FromComponentInNewPrefab`, `FromNewComponentOnNewGameObject`, etc.) there are also two extra bind methods.

* **WithGameObjectName** = The name to give the new Game Object associated with this binding.

```csharp
Container.Bind().FromComponentInNewPrefabResource("Some/Path/Foo").WithGameObjectName("Foo1");
Container.Bind().FromNewComponentOnNewGameObject().WithGameObjectName("Foo1");
```

* **UnderTransformGroup(string)** = The name of the transform group to place the new game object under. This is especially useful for factories, which can be used to create many copies of a prefab, so it can be nice to have them automatically grouped together within the scene heirarchy.

```csharp
Container.BindFactory()
.FromComponentInNewPrefab(BulletPrefab)
.UnderTransformGroup("Bullets");
```

* **UnderTransform(Transform)** = The actual transform to place the new game object under.

```csharp
Container.BindFactory()
.FromComponentInNewPrefab(BulletPrefab)
.UnderTransform(BulletTransform);
```

* **UnderTransform(Method)** = A method to provide the transform to use.

```csharp
Container.BindFactory()
.FromComponentInNewGameObject()
.UnderTransform(GetParent);

Transform GetParent(InjectContext context)
{
if (context.ObjectInstance is Component)
{
return ((Component)context.ObjectInstance).transform;
}

return null;
}
```

This example will automatically parent the Foo GameObject underneath the game object that it is being injected into, unless the injected object is not a MonoBehaviour in which case it will leave Foo at the root of the scene hierarchy.

## Optional Binding

You can declare some dependencies as optional as follows:

```csharp
public class Bar
{
public Bar(
[InjectOptional]
IFoo foo)
{
...
}
}
...

// You can comment this out and it will still work
Container.Bind().AsSingle();
```

Or, if you have an identifier as well:

```csharp
public class Bar
{
public Bar(
[Inject(Optional = true, Id = "foo1")]
IFoo foo)
{
...
}
}
```

If an optional dependency is not bound in any installers, then it will be injected as null.

If the dependency is a primitive type (eg. `int,` `float`, `struct`) then it will be injected with its default value (eg. 0 for ints).

You may also assign an explicit default using the standard C# way such as:

```csharp
public class Bar
{
public Bar(int foo = 5)
{
...
}
}
...

// Can comment this out and 5 will be used instead
Container.BindInstance(1);
```

Note also that the `[InjectOptional]` is not necessary in this case, since it's already implied by the default value.

Alternatively, you can define the primitive parameter as nullable, and perform logic depending on whether it is supplied or not, such as:

```csharp
public class Bar
{
int _foo;

public Bar(
[InjectOptional]
int? foo)
{
if (foo == null)
{
// Use 5 if unspecified
_foo = 5;
}
else
{
_foo = foo.Value;
}
}
}

...

// Can comment this out and it will use 5 instead
Container.BindInstance(1);
```

## Conditional Bindings

In many cases you will want to restrict where a given dependency is injected. You can do this using the following syntax:

```csharp
Container.Bind().To().AsSingle().WhenInjectedInto();
Container.Bind().To().AsSingle().WhenInjectedInto();
```

Note that `WhenInjectedInto` is simple shorthand for the following, which uses the more general `When()` method:

```csharp
Container.Bind().To().AsSingle().When(context => context.ObjectType == typeof(Bar));
```

The InjectContext class (which is passed as the `context` parameter above) contains the following information that you can use in your conditional:

* `Type ObjectType` - The type of the newly instantiated object, which we are injecting dependencies into. Note that this is null for root calls to `Resolve<>` or `Instantiate<>`
* `object ObjectInstance` - The newly instantiated instance that is having its dependencies filled. Note that this is only available when injecting fields or into `[Inject]` methods and null for constructor parameters
* `string Identifier` - This will be null in most cases and set to whatever is given as a parameter to the `[Inject]` attribute. For example, `[Inject(Id = "foo")] _foo` will result in `Identifier` being equal to the string "foo".
* `object ConcreteIdentifier` - This will be null in most cases and set to whatever is given as the identifier in the `WithConcreteIdentifier` bind method
* `string MemberName` - The name of the field or parameter that we are injecting into. This can be used, for example, in the case where you have multiple constructor parameters that are strings. However, using the parameter or field name can be error prone since other programmers may refactor it to use a different name. In many cases it's better to use an explicit identifier
* `Type MemberType` - The type of the field or parameter that we are injecting into.
* `InjectContext ParentContext` - This contains information on the entire object graph that precedes the current class being created. For example, dependency A might be created, which requires an instance of B, which requires an instance of C. You could use this field to inject different values into C, based on some condition about A. This can be used to create very complex conditions using any combination of parent context information. Note also that `ParentContext.MemberType` is not necessarily the same as ObjectType, since the ObjectType could be a derived type from `ParentContext.MemberType`
* `bool Optional` - True if the `[InjectOptional]` parameter is declared on the field being injected

## List Bindings

When Zenject finds multiple bindings for the same type, it interprets that to be a list. So, in the example code below, `Bar` would get a list containing a new instance of `Foo1,` `Foo2`, and `Foo3`:

```csharp
// In an installer somewhere
Container.Bind().To().AsSingle();
Container.Bind().To().AsSingle();
Container.Bind().To().AsSingle();

...

public class Bar
{
public Bar(List foos)
{
}
}
```

The order of the list will be the same as the order in which they were added with a `Bind` method. The only exception is when you use subcontainers, since in that case the list will be ordered first by the associated subcontainer, with the first set of instances taken from the bottom most subcontainer, and then the parent, then the grandparent, etc.

## Global Bindings Using Project Context

This all works great for each individual scene, but what if you have dependencies that you wish to persist permanently across all scenes? In Zenject you can do this by adding installers to a `ProjectContext` object.

To do this, first you need to create a prefab for the `ProjectContext,` and then you can add installers to it. You can do this most easily by selecting the menu item `Edit -> Zenject -> Create Project Context`. You should then see a new asset in the folder `Assets/Resources` called 'ProjectContext'. Alternatively, you can right click somewhere in Projects tab and select `Create -> Zenject -> ProjectContext`.

If you click on this it will appear nearly identically to the inspector for `SceneContext`. The easiest way to configure this prefab is to temporarily add it to your scene, add Installers to it, then click "Apply" to save it back to the prefab before deleting it from your scene. In addition to installers, you can also add your own custom MonoBehaviour classes to the ProjectContext object directly.

Then, when you start any scene that contains a `SceneContext`, your `ProjectContext` object will always be initialized first. All the installers you add here will be executed and the bindings that you add within them will be available for use in all scenes within your project. The `ProjectContext` game object is set as DontDestroyOnLoad so it will not be destroyed when changing scenes.

Note also that this only occurs once. If you load another scene from the first scene, your `ProjectContext` will not be called again and the bindings that it added previously will persist into the new scene. You can declare `ITickable` / `IInitializable` / `IDisposable` objects in your project context installers in the same way you do for your scene installers with the result being that `IInitializable.Initialize` is called only once across each play session and `IDisposable.Dispose` is only called once the application is fully stopped.

The reason that all the bindings you add to a global installer are available for any classes within each individual scene, is because the Container in each scene uses the `ProjectContext` Container as it's "parent". For more information on nested containers see here.

`ProjectContext` is a very convenient place to put objects that you want to persist across scenes. However, the fact that it's completely global to every scene can lead to some unintended behaviour. For example, this means that even if you write a simple test scene that uses Zenject, it will load the `ProjectContext,` which may not be what you want. To address these problems it is often better to use Scene Parenting instead, since that approach allows you to be selective in terms of which scenes inherit the same common bindings. See here for more details on that approach.

Note also that by default, any game objects that are instantiated inside ProjectContext will be parented underneath it by default. If you'd prefer that each newly instantiated object is instead placed at the root of the scene hierarchy (but still marked DontDestroyOnLoad) then you can change this by unchecking the flag 'Parent New Objects Under Context' in the inspector of ProjectContext.

## Identifiers

You can also give an ID to your binding if you need to have distinct bindings for the same type, and you don't want it to just result in a `List<>`. For example:

```csharp
Container.Bind().WithId("foo").To().AsSingle();
Container.Bind().To().AsSingle();

...

public class Bar1
{
[Inject(Id = "foo")]
IFoo _foo;
}

public class Bar2
{
[Inject]
IFoo _foo;
}
```

In this example, the `Bar1` class will be given an instance of `Foo1`, and the `Bar2` class will use the default version of `IFoo` which is bound to `Foo2`.

Note also that you can do the same thing for constructor/inject-method arguments as well:

```csharp
public class Bar
{
Foo _foo;

public Bar(
[Inject(Id = "foo")]
Foo foo)
{
}
}
```

In many cases, the ID is created as a string, however you can actually use any type you like for this. For example, it's sometimes useful to use an enum instead:

```csharp
enum Cameras
{
Main,
Player,
}

Container.Bind().WithId(Cameras.Main).FromInstance(MyMainCamera);
Container.Bind().WithId(Cameras.Player).FromInstance(MyPlayerCamera);
```

You can also use custom types, as long as they implement the `Equals` operator.

## Scriptable Object Installer

Another alternative to deriving from MonoInstaller or Installer when implementing your own installers, is to derive from the `ScriptableObjectInstaller` class. This is most commonly used to store game settings. This approach has the following advantages:

* Any changes you make to the properties of the installer will persist after you stop play mode. This can be very useful when tweaking runtime parameters. For other installer types as well as any MonoBehaviour's in your scene, any changes to the inspector properties at runtime will be undone when play mode is stopped. However, there is a 'gotcha' to be aware of: Any changes to these settings in code will also be saved persistently (unlike with settings on MonoInstaller's). So if you go this route you should treat all settings objects as read-only to avoid this from happening.
* You can very easily swap out multiple instances of the same installer. For example, using the below example, you might have an instance of `GameSettingsInstaller` called `GameSettingsEasy`, and another one called `GameSettingsHard`, etc.

Example:

* Open Unity
* Right click somewhere in the Project tab and select `Create -> Zenject -> ScriptableObjectInstaller`
* Name it GameSettingsInstaller
* Right click again in the same location
* Select the newly added menu item `Create -> Installers -> GameSettingsInstaller`
* Following the approach to settings outlined here, you might then replace it with the following:

```csharp
public class GameSettings : ScriptableObjectInstaller
{
public Player.Settings Player;
public SomethingElse.Settings SomethingElse;
// ... etc.

public override void InstallBindings()
{
Container.BindInstances(Player, SomethingElse, etc.);
}
}

public class Player : ITickable
{
readonly Settings _settings;
Vector3 _position;

public Player(Settings settings)
{
_settings = settings;
}

public void Tick()
{
_position += Vector3.forward * _settings.Speed;
}

[Serializable]
public class Settings
{
public float Speed;
}
}
```

* Now, you should be able to run your game and adjust the Speed value that is on the `GameSettingsInstaller` asset at runtime, and have that change saved permanently

## Runtime Parameters For Installers

Often when calling installers from other installers it is desirable to be able to pass parameters. You can do this by adding generic arguments to whichever installer base class you are using with the types for the runtime parameters. For example, when using a non-MonoBehaviour Installer:

```csharp
public class FooInstaller : Installer
{
string _value;

public FooInstaller(string value)
{
_value = value;
}

public override void InstallBindings()
{
...

Container.BindInstance(_value).WhenInjectedInto();
}
}

public class MainInstaller : MonoInstaller
{
public override void InstallBindings()
{
FooInstaller.Install(Container, "asdf");
}
}

```

Or when using a MonoInstaller prefab:

```csharp
public class FooInstaller : MonoInstaller
{
string _value;

// Note that in this case we can't use a constructor
[Inject]
public void Construct(string value)
{
_value = value;
}

public override void InstallBindings()
{
...

Container.BindInstance(_value).WhenInjectedInto();
}
}

public class MainInstaller : MonoInstaller
{