Is there any fundamental difference between using @inject vs. [Inject] dependency injection with Blazor

Viewed 674

Say I have this:

SomePage.razor:

@inject Something something
@page "/somepage"

<h1> My Page </h1>

@code {
    // Using "Something" here ...
}

Is there any fundamental difference to this:

AnotherPage.razor:

@page "/anotherpage"

<h1> My Page </h1>

@code {
    [Inject]
    Something something { get; set; }
    // Using "Something" here ...
}

Or will they both work identically, and this is just "programmer preference"?

2 Answers

the two approaches are identical. In fact the @inject syntax is simply shorthand for the [Inject] syntax

An Addendum to elaborate on @Yasseros answer:

This is a demo Razor file - Pages/Inject.razor:

@page "/inject"
@namespace Microsoft.AspNetCore.Components
@inject NavigationManager NavManager1
<h1>Hello, world!</h1>

@code {
    [Inject] private NavigationManager NavManager2 { get; set; }
    [InjectAttribute] private NavigationManager NavManager3 { get; set; }
}

Which gets pre-compiled to the following C# file - viewable in the obj folder structure at obj/debug/net5.0/Razor/Pages/Inject.razor.g.cs:

    [Microsoft.AspNetCore.Components.RouteAttribute("/inject")]
    public partial class Inject : Microsoft.AspNetCore.Components.ComponentBase
    {
        protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
        {
            __builder.AddMarkupContent(0, "<h1>Hello, world!</h1>");
        }

    [Inject] private NavigationManager NavManager2 { get; set; }

    [InjectAttribute] private NavigationManager NavManager3 { get; set; }
    [global::Microsoft.AspNetCore.Components.InjectAttribute] private NavigationManager NavManager1 { get; set; }
    }

@inject is Razor attribute markup syntax that gets translated into C# Attribute syntax. The same applies to @page translating into RouteAttribute syntax on the class.

Related