Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ctor service injection #31927

Merged
merged 4 commits into from
Feb 29, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 104 additions & 1 deletion aspnetcore/blazor/fundamentals/dependency-injection.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,110 @@ The DI system is based on the DI system in ASP.NET Core. For more information, s

## Request a service in a component

After services are added to the service collection, inject the services into the components using the [`@inject`](xref:mvc/views/razor#inject) Razor directive, which has two parameters:
:::moniker range=">= aspnetcore-9.0"

For injecting services into components, Blazor supports [constructor injection](#constructor-injection) and [property injection](#property-injection).

### Constructor injection

After services are added to the service collection, inject one or more services into components with constructor injection. The following example injects the `IDataAccess` service to obtain a list of actors for display by a component.
guardrex marked this conversation as resolved.
Show resolved Hide resolved

`TheSunmakersCtorInjection.razor`:

```razor
@page "/the-sunmakers-ctor-injection"

<PageTitle>The Sunmakers Ctor Injection</PageTitle>

<h1>Doctor Who&reg;: The Sunmakers Actors (Villains)</h1>

@if (actors != null)
{
<ul>
@foreach (var actor in actors)
{
<li>@actor.FirstName @actor.LastName</li>
}
</ul>
}

<a href="https://www.doctorwho.tv">Doctor Who</a> is a
registered trademark of the <a href="https://www.bbc.com/">BBC</a>.
<a href="https://www.doctorwho.tv/stories/the-sunmakers">The Sunmakers</a>
```

`TheSunmakersCtorInjection.razor.cs`:

```csharp
using Microsoft.AspNetCore.Components;

public partial class TheSunmakersCtorInjection(IDataAccess dataAccess)
guardrex marked this conversation as resolved.
Show resolved Hide resolved
{
private IReadOnlyList<Actor>? actors;

protected IDataAccess DataRepository { get; } = dataAccess;

protected override async Task OnInitializedAsync()
{
actors = await DataRepository.GetAllActorsAsync();
}

public class Actor
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
}

public interface IDataAccess
{
public Task<IReadOnlyList<Actor>> GetAllActorsAsync();
}

public class DataAccess : IDataAccess
{
public async Task<IReadOnlyList<Actor>> GetAllActorsAsync() =>
await Task.FromResult(GetActors());
}
guardrex marked this conversation as resolved.
Show resolved Hide resolved

public static IReadOnlyList<Actor> GetActors()
{
return new Actor[]
{
new() { FirstName = "Henry", LastName = "Woolf" },
new() { FirstName = "Jonina", LastName = "Scott" },
new() { FirstName = "Richard", LastName = "Leech" }
};
}
}
```

The service registration for `IDataAccess` is made in the app's `Program` file.

<!-- UPDATE 9.0 When the preceding example is added to the
sample apps, the naming is TBD. If this stays
TheSunmakersCtorInjection.razor, the name of the
existing injection example component might be
changed to TheSunmakersPropInjection.razor.
-->

For components implemented from the <xref:Microsoft.AspNetCore.Components.IComponent> interface:
guardrex marked this conversation as resolved.
Show resolved Hide resolved

```csharp
using Microsoft.AspNetCore.Components;

public class TheSunmakersCtorInjection2(IDataAccess dataAccess) : IComponent
{
protected IDataAccess DataRepository { get; } = dataAccess;

...
}
```

### Property injection

:::moniker-end

After services are added to the service collection, inject one or more services into components with the [`@inject`](xref:mvc/views/razor#inject) Razor directive, which has two parameters:

* Type: The type of the service to inject.
* Property: The name of the property receiving the injected app service. The property doesn't require manual creation. The compiler creates the property.
Expand Down
Loading