简体   繁体   中英

Blazor wasm dependency injection - null http client

I'm creating a dotnet 6 blazor wasm website (core hosted) that uses B2C for auth, but having trouble with http client.

In program.cs I have the following for DI:

builder.Services.AddHttpClient<IBbtDataService, BbtDataService>(client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

This Bbt service should be injected into the code behind for the FetchBbtData page shown below:

[Authorize]
public partial class FetchBbtData
{
    [Inject]
    public IBbtDataService BbtDataService { get; set; }
    public IEnumerable<ClientOrg> ClientOrgs { get; set; }

    protected async override Task OnInitializedAsync()
    {
        ClientOrgs = (await BbtDataService.GetClientOrgList()).ToList();
    }
}

The code for the BbtDataService is as follows:

public class BbtDataService : IBbtDataService
{
    private readonly HttpClient httpClient;

    public BbtDataService(HttpClient httpClient)
    {
        httpClient = httpClient;
    }

    public async Task<IEnumerable<ClientOrg>> GetClientOrgList()
    {
        return await httpClient.GetFromJsonAsync<IEnumerable<ClientOrg>>($"api/clients");
    }
}

If I put a breakpoint on the constructor of the BbtDataService I caan see that the httpClient parameter is valid and contains the correct base url. However, when execution then hits another breakpoint in the GetClientOrgList method, the value of the private readonly field httpClient is null - even though this was set in the constructor.

Anyone see where I went wrong?

You are assigning the parameter to itself. Add 2 _ :

private readonly HttpClient _httpClient;

public BbtDataService(HttpClient httpClient)
{
   _httpClient = httpClient;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM