Allow constructor parameter injection for components #22209
Labels
area-blazor
Includes: Blazor, Razor Components
enhancement
This issue represents an ask for new feature or an enhancement to an existing one
✔️ Resolution: Duplicate
Resolved as a duplicate of another issue
Status: Resolved
Milestone
Currently blazor only allows injecting services into components using property injection via the
[Inject]
attribute.However this has a number of disadvantages over constructor injection
The compiler warns if you declare you service as non-nullable, and nullable reference types are enabled. You have to manually suppress the warning.
You cannot declare the services readonly, since they need to be set by the injector.
If you create the component manually (perhaps for unit testing), there is nothing to guarentee you will set the services. Even worse - you often can't since the properties are usually private. You have to declare two constructors - one parameterless, and one which sets all the services. This is needless code duplication, and means that test and app code go through different paths, which is undesirable.
The constructor is a place where you can validate all your services, and do transformations on them. Perhaps, you don't want to store your services, but just call one service with another service, and store the result. Constructors are a good place to do that, with property injection this is tricky.
Proposal
If there is a single constructor, use it for dependency injection. It is an error if any of the parameters cannot be resolved. It is an error if there are multiple constructors, none of which are parameterless, unless one of them is marked with
[Inject]
. After the construction, property injection takes place.The text was updated successfully, but these errors were encountered: