Conditional Bindings - mariaheine/Zenject-But-Wiki GitHub Wiki
In many cases you will want to restrict where a given dependency is injected. You can do this using the following syntax:
Container.Bind<IFoo>().To<Foo1>().AsSingle().WhenInjectedInto<Bar1>();
Container.Bind<IFoo>().To<Foo2>().AsSingle().WhenInjectedInto<Bar2>();
Note that WhenInjectedInto
is simple shorthand for the following, which uses the more general When()
method:
Container.Bind<IFoo>().To<Foo>().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 toResolve<>
orInstantiate<>
-
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 inIdentifier
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 theWithConcreteIdentifier
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 thatParentContext.MemberType
is not necessarily the same as ObjectType, since the ObjectType could be a derived type fromParentContext.MemberType
-
bool Optional
- True if the[InjectOptional]
parameter is declared on the field being injected