uid | title |
---|---|
Tutorial.Injection.Constructor.Default |
Default Constructor |
A Default called a constructor with no parameters. It could be explicitly defined on a Type or if Type has no defined constructors, C# will implicitly create one for you.
To configure resolution of a Type with a default constructor you need to register that Type with Injection Constructor Member which takes no parameters.
Consider the following Type:
[!code-csharp class Service]
Class Service
is a plain type with three accessible constructors. First constructor is a default constructor with no parameters, second and third constructors take one parameter each.
If you try to resolve this class with no registration, Unity will select one of the constructors with parameter. You can not guarantee which one it will select because both have the same number of parameters and each could be satisfied with dependencies.
Tip
If Diagnostic is enabled, it will throw an ambiguous constructor exception.
To prevent ambiguity, or if you need to execute default constructor, you can register this Type and instruct the container to invoke default constructor during resolution. In simplest form this registration will look like this:
[!code-csharp Register Service]
Note
Of corse you could add other instructions like mapping, name, etc. to the registration but for simplicity it is omitted in this example.
Once you register the Service
with the container, you can resolve it normally:
[!code-csharp Resolve Service]
At first resolution the container will create a pipeline which invokes a default constructor to create the Service
and will be using it for all subsequent resolutions.
Unity can register and create Generic types. It allows to register Closed and Open Generics and can resolve constructed types based on these.
The principle for registering of default constructor is exactly the same as for plain types. Consider the following Type:
[!code-csharp class Service{T}]
Class Service<T>
is an open generic type with two constructors. First constructor is a default constructor with no parameters and second takes one parameter.
Normally, Unity will create this Type by executing most complex constructor. To force Unity to use default constructor you need to register Service<T>
and instruct the container to invoke it during resolution. You can register constructed generic based on Service<T>
like this:
[!code-csharp Register Service{object}]
Or you can register Open Generic Type:
[!code-csharp Register Service{T arg}]
If you resolve Service<object>
:
[!code-csharp Resolve Service]
either registration will invoke the default constructor.
- Implicit Constructor Registration
- Constructor Annotation
- Select constructors by parameters count
- Select constructors by parameter types
- Select constructors based on injected values