Register Factory
Typically, in a DI container, the Factory pattern can be used to stabilize the dependency resolution.
For example, if you create a factory like the following, dependency resolution will happen only once. Dependency resolution will not occur during instance creation.
VContainer allows to register a Func<>
delegate for the creation of an instance. This is especially useful in scenarios where the instance is created at any time during execution, or multiple instances are created at any time.
It is useful to create your own Factory class like the one above.
If your Facotry class is simple enough, you can also use the Func<>
injection feature of VContainer.
Func<>
Factory that requires only runtime parameters#
Register We can resolve like below:
Func<>
Factory that requires container dependencies and runtime parameters#
Register This method required 2 params
Func<>
: Receives Container and returns Factory.Lifetime
: Determines how often the Factory is generated. (that is, how often the outer Func is executed.)
We can resolve like below:
In this case, container.Instantiate etc. are also useful.
See Use Container directory more information.
note
Func <>
factory is like a short hand.
In complex cases, consider defining and registering your own factory class。