Optional Binding - mariaheine/Zenject-But-Wiki GitHub Wiki
You can declare some dependencies as optional as follows:
public class Bar
{
public Bar(
[InjectOptional]
IFoo foo)
{
...
}
}
...
// You can comment this out and it will still work
Container.Bind<IFoo>().AsSingle();
Or, if you have an identifier as well:
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:
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:
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);