Skip to content

Allow constructor parameter injection for components #22209

@YairHalberstadt

Description

@YairHalberstadt

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

  1. NRTs
    The compiler warns if you declare you service as non-nullable, and nullable reference types are enabled. You have to manually suppress the warning.
  2. Immutablility
    You cannot declare the services readonly, since they need to be set by the injector.
  3. Manual construction
    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.
  4. Validation
    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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ✔️ Resolution: DuplicateResolved as a duplicate of another issueStatus: Resolvedarea-blazorIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing one

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions